Part Number Hot Search : 
STM32F 222E3 BXMF1018 LTC155 E101MPD 973506 M29F400B GD54HC76
Product Description
Full Text Search
 

To Download AN1105 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  AN1105/0801 1/100 version 1.3 AN1105 application note st7 pcan peripheral driver by central european mcu support introduction the controller area network (can) norm defines a fast and robust serial bus protocol, suited for local networking of intelligent devices such as microcontrollers, sensors and actuators. it is now widely used, mostly in the automotive domain, but also for home automation and indus- trial equipment control. several members of the st7 mcu family have a built-in can peripheral named pcan, which allows them to be used as nodes in a can network. a software driver provided is by st to help you start designing and writing applications using the st7 pcan cell. the purpose of the following application note is to explain to you how to use the driver, and how it works. thus, you can either build your software from the provided files, or modify them to meet specific needs. you will find in this application note: C a brief description of the can protocol C an overview of the pcan peripheral C the complete description of the user interface C the step-by-step development of an example application using the driver features C a technical report including a description of algorithms and internal data types 1
2/100 table of contents 100 introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 can communication protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.1 general characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.1.1 protocol properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.1.2 can in the osi reference model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 can frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2.1 can data frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.2.2 can remote frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.2.3 can error frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.2.4 can overload frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.3 physical representation of data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.3.1 bit stuffing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.3.2 bit timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 1.4 arbitration phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.4.1 arbitration phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1.4.2 message acknowledgement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.5 error management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.6 st7 pcan peripheral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 1.6.1 main features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 1.6.2 cell behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2 can driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.1 user interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.1.1 files furnished . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 5 2.1.2 architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.1.3 principle of use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.1.4 interrupts (its) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.1.5 user interface description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 how to use the can driver: a demo application . . . . . . . . . . . . . . 27 2.2.1 application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.2.2 cell configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.2.3 implementing the notification functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.2.4 transmissions outside the can interrupt function . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.2.5 important: reentrant functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3 detailed description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 3.1 user interface functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 3.2 internal functions and data types . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.2.1 internal data types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.2.2 internal routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 3.3 a few words about driver performance . . . . . . . . . . . . . . . . . . . . 55 3.3.1 cpu load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 3.3.2 code size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 2
3/100 table of contents 4 driver code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.1 can.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.2 can.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.3 can_custom.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 4.4 can_custom.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 4.5 can_hr.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 1
4/100 st7 pcan peripheral driver 1 can communication protocol in the early 80s, electronic applications appeared in the automotive world. the need gradually arose to establish real-time communications between various types of on-board equipment. in 1986, the can bus protocol, designed by robert bosch gmbh, was presented to the public for the first time. in 1989, the first silicon implementing the protocol was issued and in 1991, the first car equipped with a can network was produced. today, the protocol is an international norm (iso 11898). its relative simplicity, the wide avail- ability of products and services in terms of chips, software libraries, starter kits, courses and training makes the development of applications relatively fast and cheap. the can protocol provides the user with very reliable communication, with a powerful error detection/confinement mechanism. it allows baud rates up to 1mbaud (for networks of up to 40m) which makes it able to support real time applications. the bus can of course be config- ured with lower speeds for larger networks (50kbaud for networks up to 1km long for ex- ample). there were more than 150 million can nodes installed at the beginning of 1999. 1.1 general characteristics 1.1.1 protocol properties n asynchronous serial bus (see bit timing on page 9 ) C no clock signal is transmitted, allowing a two-wires (high speed can see iso 11898) or even one-wire communication (low speed can, see iso 11519) C each node resynchronizes itself on every falling edge occurring on the bus. n csma/ca (carrier sense multiple access/collision avoidance) C several nodes can request the bus simultaneously (csma). C when such a situation occurs, there is no loss of data and the message with the highest priority is immediately sent (ca). n multimaster capability (see arbitration phase on page 10 ) C every can node in the network is able to transmit data. C the arbitration mechanism is decentralized. n object oriented communication C each message on the bus carries its own identifier which is an 11-bit (or 29-bit) number. this field describes the content of the message. it is not an address. C consequently, a transmitter doesnt address data to a peer but simply broadcasts its data. each node in the network picks off data from the bus when it recognizes an identifier that concerns it.
5/100 st7 pcan peripheral driver n message prioritization C the identifier of a message also indicates the priority of its carrier. during the arbitration phase, a bitwise comparison of the different identifiers is performed. the message with the higher identifier being the more urgent, it wins the arbitration and is immediately transmit- ted. n error management system (see error management on page 11 ) C detection: every node continuously monitors the bus, even if it is not concerned by the cur- rent transmission, to detect potential violations of the protocol. C signalization: any node detecting an error, signals it to its peers and aborts the current transmission meanwhile. the sender automatically retries transmission within a certain amount of time. thus, the consistency of data throughout the network is preserved. C confinement: each node implements counters which are incremented (or decremented) after each detection of an error (or successful operation). a defective station can then switch itself off when its counters reach a certain value, and thus stop disturbing the bus operations. 1.1.2 can in the osi reference model the protocol occupies parts of the two lowest levels (the physical and data link layers) of the 7-level iso/osi (open system interconnection) telecommunications reference model. table 1. iso/osi standard telecommunication layers in this reference model, the data link layer deals with physically passing data from one node to another. it defines arbitration, message framing, error management and transmission timing for example. the physical layer deals with putting data on the physical network, and with taking it off. con- sequently, it defines signal levels and timings, as well as the transmission support (wire types, connectors, etc.). the can protocol splits the data link layer into object and transfer sublayers, corre- sponding to the iso/osi logical link control and medium access control sublayers. the transfer layer is the interface between the user application and the can. the object layer osi layer osi model can protocol 7 application no (user defined) 6 presentation no (user defined) 5 session no (user defined) 4 transport no (user defined) 3 network no (user defined) 2 data link yes 1 physical partly 1
6/100 st7 pcan peripheral driver manages frame shaping and acknowledgment mechanisms, bus arbitration and checks the formal correctness of the data transmitted and received. the physical layer is only partly defined, and the user is free to choose the transmission me- dium for example. figure 1. layered architecture of can (iso 11898 definition) 1.2 can frame there are four different can frame types: data frame , error frame , remote frame and overload frame there are also two versions of the can protocol: 2.0a (or base format) and 2.0b (or extended format). the 2.0b standard introduces an extended data frame with a longer identifier. both frame types coexist on a can 2.0b bus, and its nodes must be at least able to recognize and acknowledge both. we will only describe here the 2.0a format, or base format. 1.2.1 can data frame the can data frame is used for data transmission and contains the following fields: n a start of frame field, consisting of one bit. n a 12-bit arbitration field , including: C an 11-bit identifier data link layer physical layer l ogical l ink c ontrol acceptance filtering overload notification recovery management m edium a ccess c ontrol data encapsulation/decapsulation frame coding (stuff/destuff) medium access management error detection error signaling acknowledgement serialization/deserialization p hysical l ayer s ignaling bit encoding/decoding bit timing synchronization p hysical m edium a ttachment driver/receiver characteristics m edium d ependent i nterface connector fault confinement ( mac - l ayer m anagement e ntity) bus failure management ( pls - l ayer m anagement e ntity)
7/100 st7 pcan peripheral driver Ca rtr bit used to differentiate data and remote frames. it is dominant in a data frame. n a 6-bit control field , including: C a 4-bit data length code bits giving the size (in bytes) of the data field C1 id entifier e xtension ( ide ) bit (dominant for can 2.0a frame) and 1 bit reserved for fur- ther development. n a data field of up to 8 bytes. n a 16-bit long crc field . the cyclic redundancy check (crc) is based on a bch encoding. n a 2-bit acknowledgment field. the transmitters sends it as all recessive. (see message acknowledgement on page 11 ) n a 7-bit end-of-frame field. the interframe space (or intermission) is the minimum amount of time between two consecu- tive transmissions. figure 2. can data frame 1.2.2 can remote frame the can remote frame is used to request data. this frame has the same overall constitution as the data frame. however, in this case, the remote bit (rtr) is recessive and there is no data field . 19 bits 25 bits 11-bit identifier dlc 15 bits bus idle 3 bits 7 bits eof ack crc field control field arbitration field d r sof rtr = 0 ide = 0 ack delimiter ack slot crc delimiter interframe space data field data 0..64 bits
8/100 st7 pcan peripheral driver figure 3. can remote frame 1.2.3 can error frame the can error frame is sent by a node as soon as it detects a protocol violation in the current operations on the bus. this frame is composed of 6 successive dominant bits (active error flag) or recessive (passive error flag), followed by 8 recessive frame delimiter bits. the cur- rent error state of the node sending the error frame (see section 1.5 "error management" ) will determine whether it is an active frame (node in error active state) or a passive frame (node in error passive state). 1.2.4 can overload frame the can overload frame can be sent during the interframe space to delay the next transmis- sion on the bus. this frame has the same constitution as the active error frame. figure 4. can error/overload frame 1.3 physical representation of data the can data is encoded with nrz (non return to zero) code. the two logical levels used are named dominant (0) and recessive (1) . because the can cells are connected on the bus according to the wired-and principle, it follows that the default bus state is recessive, and that 19 bits 25 bits 11-bit identifier dlc 15 bits bus idle 3 bits 7 bits eof ack crc field control field arbitration field d r sof rtr = 1 ide = 0 ack delimiter ack slot crc delimiter interframe space 3 bits bus idle or data frames 8 bits interframe space error/overload delimiter max. 12 bits error/overload 6 bits r d data frame error detection flag
9/100 st7 pcan peripheral driver transmission of a dominant bit forces this state to dominant, no matter how many other nodes are transmitting recessive bits. 1.3.1 bit stuffing once built, a frame is passed to the transfer sub-layer, where the crc is calculated. then, stuffing bits are inserted in the frame. each time five consecutive bits of the same logical level are detected, a bit of the opposite value is inserted. this is used to generate a minimum edge rate on the bus for resynchronisation purpose (see bit timing on page 9 ). figure 5. bit-stream nrz code & bit stuffing 1.3.2 bit timing the can standard divides the bit time into four segments: C a synchronisation segment (sync), C a propagation segment (prop), C a phase buffer 1 segment (tseg1), C a phase buffer 2 segment (tseg2), C each segment is divided into time quanta. the synchronisation segment lasts, by defini- tion, 1 time quantum. figure 6. can bit segments the can communication is asynchronous, i.e. no clock signal is sent together with data. each node in the network maintains its own bit timing calculated from the internal clock of the de- vice. 1 0 1 1 1 0 1 0 1 0 0 0 0 0 1 0 0 0 1 1 0 1 1 1 1 1 0 0 0 1 stuff bits sync prop tseg1 bit time sample point tseg2 next bit previous bit
10/100 st7 pcan peripheral driver to deal with signal phase variations on the transmission line due mostly to desynchronization between clocks of bus participants, tseg1 and tseg2 are of variable length. a resynchroni- zation of the local clock occurs on every recessive-to-dominant state change. if such a change arises before (or after) the sync segment expected by the cell, tseg1 (or tseg2) is length- ened (or shortened) to correct the detected variation. if the edges occur during the sync seg- ment, the node assumes that it is synchronized. the prop segment takes into account the maximum propagation time of the signal on the network, ensuring that all the nodes sample the same bit at the same time. the sampling point of the bit takes place between tseg1 and tseg2. 1.4 arbitration phase 1.4.1 arbitration phase all the cells connected on the can network are likely to transmit a message at any time. a cell can initiate a transmission only when the bus is idle. on transmission of a message, a cell si- multaneously monitors the state of the bus to detect potential problems. if the bus is idle, any cell that is ready for transmission begins to send its data. the other nodes listen. if the bus is already in use when a cell requests it, the cell waits until the end of the current transmission. then, all the nodes that are ready to transmit begin their transmission. if a dom- inant and a recessive bit are sent in the meantime, the first one erases the second. this causes the cell that is sending the recessive bit to lose the arbitration and switch to reception mode. this way, messages with the highest identifiers are sent before the others. this mech- anism also prevents collisions occurring on the bus, which saves bandwidth. this is referred to as non-destructive bitwise arbitration. figure 7. arbitration example: node 1 wins node 1 node 2 node n can bus recessive dominant
11/100 st7 pcan peripheral driver 1.4.2 message acknowledgement any cell having received a message correctly, regardless of the result of the acceptance test, must acknowledge it by sending a dominant bit during the ack slot of the current frame, thus overwriting the recessive bit sent by the current transmitter. 1.5 error management the error management system of the can protocol is proof of the protocols robustness. this system provides a way to automatically distinguish permanent failures from sporadic errors. it can lead to self-disconnection of a failing node from the bus. this feature is named error con- finement . an error is defined as a violation of one of the protocols rules. it can happen after one of following events: C bit error: a transmitter detects a difference between the actual bus state and what it sends. C acknowledgement error: a frame is not acknowledged (ack slot recessive). C stuffing error: more than five identical bits were received consecutively. C crc error: the crc received does not match the calculated crc. C format error: one of the fixed-format fields (crc delimiter, ack delimiter, end of frame) does not have the expected format. an error frame is immediately sent by all the cells that have detected an error on the bus. note that the error frame does not yield to the stuffing rule. upon reception of this frame, all cells in the network detect a stuffing error and react by sending an error frame. the dominant state of the bus caused by the occurrence of an error can last at most 12 bits (case when a node de- tects the error only at the end of the error flag). the error confinement system is based on two counters: C a transmissionerror counter (tec) C a receptionerror counter (rec) the rules handling the counters are basically the following: C when an emitting node detects an error, it increments its tec and sends an error frame. C when a receiving node detects an error it increments its rec and sends an error frame. C when a transmission is successful, the tec counter is decremented. C when a reception is successful, the rec counter is decremented. note : the complete set of rules is quite complicated taking into account the possibility of receiving over- load frames, etc. consequently, its beyond the scope of this document. this document describes the basic reactions of the cell. for more information, refer to the original robert bosch gmbh doc- ument or to the iso 11898 norm. the behaviour of the cell concerning the state of the counters is shown in the following dia- gram.
12/100 st7 pcan peripheral driver figure 8. can error states when both counters contain values between 0 and 127, the can node is in error active state , which means that it can send and receive normally. if it detects an error, it will send ac- tive error flags. when one of the two counters reaches a value between 128 and 255, the node is in error passive state . it will go on receiving and sending normally but will only be authorized to send passive error flags. therefore, if this node causes trouble by sending unjustified error frames, it will not disturb the network for too long. when one of the counters reaches a value over 255 (i.e. it overflows), the can node enters bus off state . it is then physically disconnected from the bus. it can go back to active mode if it successfully detects 128x11 consecutive recessive bits on the bus. 1.6 st7 pcan peripheral 1.6.1 main features the st7 pcan peripheral implements a can 2.0b passive protocol. this means that ex- tended frames are recognized and acknowledged, but cannot be saved nor processed by the microcontroller. C the pcan peripheral is based on three 10-byte hardware buffers that can be used either for transmission or reception. they are prioritized in the increasing priority order 1 to 3 for transmission and 3 to 1 for reception. each buffer has a control register indicating if a job is pending, if new data has been received or if the buffer is currently being written/read. a bit in this register is used to lock the buffer for transmission (see st72511 datasheet p.116). C the baud rate is programmable up to 1 mbps . the length of the bit synchronisation fields is also programmable. the baud rate is configured by setting three values: the size of time quanta (in clock ticks) and the length of the two synchronization segments (in time quanta). see st72511 datasheet p.114, b aud r ate p rescaler r egister and b it t iming r egister. error active error passive bus off tec >255 128 blocks of 11 suc- cessive recessive bits tec>127 or rec>127 tec<127 and rec<127
13/100 st7 pcan peripheral driver C two 11-bit filters and two 11-bit masks are used for hardware filtering with identifier/iden- tifier-range definition. the masks define which bits of the filters are to be ignored and which are to be tested. any message whose identifier does not match will not be saved in the buff- ers. C the cell automatically enters low power mode after the reception of 20 recessive bits, or standby state on command. C the pcan peripheral can wake-up the st7 microcontroller from halt mode . see section 2.1.3.2 "waking-up from halt mode" to learn how. C the can error confinement feature, as defined by the can protocol, is fully implement- ed , with read-only access to the counters and maskable interrupts on state changes. once in bus off state, the cell automatically returns to bus active state if it has detected 128x11 recessive bits on the bus (see section 2.1.3.1 "controlling status changes" ). see note on section 2.1.3.2 "waking-up from halt mode" to see how the driver can provide you with full control over the bus-off to bus-active transition. C the three send/receive buffers, filters, masks and counters are mapped at a unique ad- dress space , allowing efficient software access. 1.6.2 cell behaviour in standby state, the node monitors the bus in order to detect a dominant pulse that could gen- erate an interrupt (see st72511 datasheet p.112, interrupt control register, scie bit). when the run bit of the control status register is set (see st72511 datasheet p.113), the cell leaves standby mode. it then enters resynchronization mode before it really starts running. if the wkps bit of the control/status register is set, then the cell will send a dominant pulse when it wakes up. you can choose between two resynchronization durations: 11 recessive bits if the fsyn bit of the csr is set or 128*11 recessive bits if not (see st72511 datasheet p.113). if the cell resynchronizes after leaving bus-off state, it will wait 128*11 recessive bits, whatever the value of fsyn may be. to send data, a buffer has to be selected first by writing to the page selection register (see datasheet p. 114). then it has to be locked for transmission by setting the lock bit in the buffer control/status register (see datasheet p.116: lock bit and rdy bit). then data can be written in the buffer registers: identifier, data length code, data bytes. writing in the seventh data register starts transmission. received data is automatically stored in one of the buffers configured for reception (lock bit reset) each time a message identifier matches the hardware filters of the pcan cell, and pro- vided that this buffer is marked as free (rdy bit reset. see datasheet p.116: lock bit and rdy bit). the masks/filters can be configured through the filter/mask high/low registers (see datasheet p.117).
14/100 st7 pcan peripheral driver any event (successful transmission, data reception, error, state change, overrun) can gen- erate a maskable interrupt. the interrupt control register (see datasheet p.112) allows you to set/reset these masks. note that each buffer has its own reception interrupt, allowing the data to be saved rapidly. note : for further, more detailed explanations, please read the st72511r/st72512r/st72532r datash- eet, downloadable from the st web site, http://mcu.st.com . figure 9. st7 pcan state diagram standby resynchronisation wake-up pulse generation idle reception transmission error r un run run & wkps & wkps reset r un tx ok arbitration lost rx ok start of frame rx error tx error busoff busoff fsyn & busoff & 11 recessive bits or... (fsyn | busoff) & 128*11 recessive bits
15/100 st7 pcan peripheral driver 2 can driver to quickly start developing your own can applications using the st7 pcan peripheral, stmi- croelectronics provides you with a driver. the source code (can.h and can.c) is given as an ex- ample, and can therefore be used as provided or be modified to fit specific needs. there are two customization files which make the drivers functionality flexible and able to meet a wide range of needs. the entire processing is interrupt driven, so no polling is required. the application is notified of can events through function calls from the interrupt routine. to immediately use the driver, without modifying its structure, see section 2.2 "how to use the can driver: a demo application" . the following sections will explain the details of the driver architecture and describe all the functions and data types implemented in the software. 2.1 user interface 2.1.1 files furnished the driver consists of five files: C can.c . driver function definitions and internal data types. this file may not be modified. C can.h . header file of can.c. this file may not be modified. C can_hr.h . hardware description (register mapping of the st7 mcu memory space). this file is hardware dependent and must not be modified. C can_custom.c . frames of customization functions. they are called (some optionally) by the driver to notify the application of events when some user-specific processing is required (for example on reception of data). this file has to be completed by the user. C can_custom.h . contains a pre-processor directive list ( #define types) which allows user customizations to be taken into account at compilation time. this file has to be modified by the user. 2.1.2 architecture the cell is statically configured with one transmission buffer and two reception buffers, which reduces the need for processor responsiveness in reception. for the same purpose, a 3-message deep transmission fifo is implemented. it is not acces- sible by the user, and is automatically managed by the software. the entire processing is interrupt driven. the user can choose which interrupts are to be taken into account and which are not, due to the compilation options in can_custom.h. some inter- rupts request an immediate answer from the application, e.g. a reception event. to avoid having the user modify the interrupt routine (in can.c), the routine calls one of the notification
16/100 st7 pcan peripheral driver functions defined in can_custom.c on certain events. the user only has to enter these func- tions according to his needs before compiling the software. 2.1.3 principle of use during compilation, the values of the hardware control registers are calculated by the preproc- essor according to the compilation options selected in can_custom.h. if the software filtering feature is enabled, the values of accepted identifiers have to be entered by the user as a list in can_custom.h (see filtering on page 29 ) the functions in can.c are compiled or not, according to the selected #define directives. (the unwanted ones are simply left as comments). figure 10. driver customization system during the first initialization (performed using the can_first_init function), the peripherals registers are written with the values defined at compilation time, the transmission fifo is ini- tialized and the cell starts (a wake up by bus can be chosen). then: C the can_transmit_request function initiates a transmission which begins with an in-queu- ing of the message to be sent. then, hardware buffer no.1 (the static transmission buffer) is filled according to hardware requirements. (see section 1.6.2 "cell behaviour" ). #define init_brpr 0x11 ... #define status_change_notification ... //#define debug #ifdef status_change_notification void can_bus_passive_notification(void) { //to implement if defined } #endif ... ... #ifdef debug void can_overrun_notification(void) { //to implement if defined } #endif can_custom.h file can_custom.c file compiled not compiled brpr register 0x11 compilation compilation st7 registers
17/100 st7 pcan peripheral driver C the can_switch_off and can_sleep functions are used to switch the cell to standby mode. the first function kills any pending jobs and erases all data in the reception buffers, even if the data is unread. the second function is executed the same way as long as no work is in progress, the transmission fifo is empty and all reception buffers have already been read. these two functions also define the way the cell will be woken-up: either by bus or by soft- ware (by enabling or disabling the corresponding interrupt). they can help you to manage status changes by controlling the transition between bus off and bus active states (see sec- tion 2.1.3.1 "controlling status changes" ). C can_switch_on resets the cell and returns to run mode. it can also place the cell in a state waiting for a dominant pulse to be woken-up. C can_get_status returns the current status of the peripheral (run, standby, error passive...) C can_get_tec returns the current content of the transmission error counter. C can_get_rec returns the current content of the reception error counter. 2.1.3.1 controlling status changes your application can be notified by the driver when the error state of the cell changes. (see compilation options on page 25 ). if you dont want the microcontroller to directly resynchro- nize after leaving bus-off state for example, you can call the can_switch_off function from in- side of the can_bus_off_notification function (see can_custom.c file on page 26 ), then perform any operations you want before calling the can_switch_on function to restart the pe- ripheral. 2.1.3.2 waking-up from halt mode if you want to switch the st7 to halt mode and have it woken-up by the can, the correct in- terrupt routine must be enabled. before switching to halt mode, call the can_sleep or can_switch_off function with the bus_wakeup parameter that is used to enable the can interrupt on the bus dominant state while in standby state. then, enter the can_dominant_bit_reception_notification function to customize the waking up of the microcontroller. note: see st72511 datasheet p.37 for more information about halt mode. 2.1.4 interrupts (its) once the interrupt routine is entered, the first thing you want to know is what triggered the event? priority is then given to reception if more than one it has occurred simultaneously, un- less the debug compilation option was set. in this case, the error its are processed first. C in the event of a transmission it, the driver tries to send the following message in the queue, if its not empty. the driver then notifies the application of the event before leaving the rou- tine.
18/100 st7 pcan peripheral driver figure 11. transmission it procedure C in the event of a reception it, after having found which buffer is involved, the driver performs an optional software filtering, then notifies the application. if the cell received a remote frame, the can_remote_reception_notification function is called. otherwise, if the cell received data, the can_request_buffer function is called to request a buffer from your application. after the buffer is filled, the driver calls the can_data_reception_notification function to no- tify you that the data is ready. if the debug option is set, the can_reception_status func- tion is called just before leaving the it routine, which passes the status of the reception processing procedure (error, success...) as a parameter. this is used to detect the causes of any problems. see can_custom.h file on page 24 for more information about notification routines. figure 12. reception it procedure can bus successful transmission it notification error notification, only if debug defined fills buffer with next data clears flags next transmission attempt what see driver processing you 1 3 4 5 2 application st driver st7 hardware can bus successful reception it notification: error notification only if debug defined save data in software buffer buffer free for what see driver processing reception data or remote notification (case data) (case data) + clears flags you application st driver st7 hardware 1 2 3 4 5 next
19/100 st7 pcan peripheral driver C error its are only processed if the debug option was chosen in can_custom.h. then, the application is notified of any other events through function calls. (functions entered in can_custom.c). 2.1.5 user interface description this section describes the user interface in a black-box way. the parameters and the return values of the function declared in can.h and can_custom.h are described in this section. for a complete description of the algorithms and internal data type variables, please see section 3 "detailed description" . 2.1.5.1 data-type variables can_buffer -type variables typedef struct can_buffer{ u16msg_identifier; can_data_size data_size; u8 can_msg_data[can_max_data_size]; can_bool buffer_rw; can_bool buffer_free; }can_buffer; software representation of can data. the translation into hardware buffers is performed by the driver. a variable of this data-type must be passed to the driver each time it is requested by the can_request_buffer notification function (see functions called unconditionally on page 26 ). otherwise, data in the hardware buffer will be lost. a pointer to this structure is also used as parameter of the can_transmit_request function (see functions on page 21 ). C msg_identifier: 2 bytes field containing the identifier of the can message. the identifier is stored in the 12 most significant bits. the 4 least significant bits must be zero. the u16 type means 2 bytes unsigned variable and is defined in lib.h. C data_size: 1 byte field containing the length of the data in the message (in bytes). the can_data_size type is an enum type (see below for its description). C can_msg_data : array of 8 bytes containing the data to be sent. the u8u16 type means 1 byte unsigned variable and is defined in lib.h. C buffer_rw : this boolean variable is to be used as a flag to prevent simultaneous writing/ reading on the structure. it is checked and modified by the driver each time an operation is being performed on the buffer. if ctrue, the structure will not be read or written. if cfalse, it can be used. always check/modify this variable in your application for this pur- pose. C buffer_free : boolean variable used to mark if the data in the buffer can be overwritten or not. it has to be used as the security by the users application. if cfalse, the driver will refuse to perform any write operation on the data in the structure and return an error code.
20/100 st7 pcan peripheral driver if ctrue, the data can be modified. take care to check and/or initialize it before passing a buffer to the driver. init_data -type variables typedef struct { u8 brpr_init; u8 btr_init; u8 fhr1_init; u8 flr1_init; u8 mhr1_init; u8 mlr1_init; u8 fhr0_init; u8 flr0_init; u8 mhr0_init; u8 mlr0_init; u8 }init_data; this structure contains the value of registers that can be reinitialized when switching on the cell after a passage in standby state (see section 2.1.5.2 "functions" , can_switch_on). it is used for hardware initialization. C brpr_init : value of the canbrpr register (set length of a can time quantum in number of cpu clock ticks). see bit timing on page 9 . C btr_init : value of the canbtr register (length of both time segments 1 and 2 in number of time quanta). see bit timing on page 9 . C fhr1_init : value of filter 1 high register. C flr1_init : value of the filter1 low register. C mhr1_init : value of the mask 1 high register. C mlr1_init : value of the mask 1 low register. C fhr0_init : value of filter 0high register. C flr0_init : value of the filter 0 low register. C mhr0_init : value of the mask 0high register. C mlr0_init : value of the mask 0low register. enum -type variables the names of the variables are in principle self-explanatory. typedef enum {dlc0,dlc1,dlc2,dlc3,dlc4,dlc5,dlc6,dlc7,dlc8,remote_frame}can_data_size; possible values of the can_message data_size field (see can_buffer -type variables on page 19 ) typedef enum
21/100 st7 pcan peripheral driver {can_run,can_standby,can_bus_active,can_bus_passive,can_bus_off}can_status; describes the different states of the cell. typedef enum {cfalse=0,ctrue=1}can_bool; custom boolean type variable. typedef enum {bus_wakeup,soft_wakeup}wakeup_cause; possible parameters of the can_sleep and can_switch_off functions. (see section 2.1.5.2 "functions" .) typedef enum{can_sleep_error,can_sleep_success,can_switch_on_succes,can_switch_on_fa ilure}can_switch_error; possible values returned by can_sleep, can_switch_off and can_switch_on functions (see section 2.1.5.2 "functions" ) typedef enum {can_init_success,can_init_failure}can_init_error; possible values returned by can_first_init function (see section 2.1.5.2 "functions" ) typedef enum {can_transmit_success,can_transmit_failure,can_transmit_no_msg,can_fifo_full ,can_transmit_buffer_full,can_transmission_error_it}can_transmit_error; error codes used in transmission functions.(see section 2.1.5.2 "functions" ) typedef enum {can_receive_success,can_receive_remote,can_illegal_identifier,can_filtering _failure,can_receive_failure,can_buffer_in_use,can_no_buffer,can_rcv_buffer_ not_ready}can_receive_error; error codes used in reception functions. (see section 3.2.2 "internal routines" ). note : with some compilers, an option is used to define the size, in bytes, of enum-type variables. we rec- ommend selecting 1 byte, if possible, to save memory space. you can see in which case the different error codes are returned by the functions by studying the flow charts in section 3.2.2 "internal routines" for internal functions and section 3.1 "user interface functions" for user interface functions. you also find this information in the arrays of section 2.1.5.2 "functions" for user-interface routines and section 3.2.2 "internal routines" for internal routines. 2.1.5.2 functions can_init_error can_first_init(void): input -- output error status
22/100 st7 pcan peripheral driver void can_it_dis(void): can_status can_get_status (void): u8 can_get_tec(void): u8 can_get_rec(void): can_switch_error can_switch_off(wakeup_cause): description can cell power-on initialization routine. during its execution, all registers are initialized with values entered in can_custom.h or calculated from the compilation options chosen it initializes the transmission queue. this function must be called in the main routine prior to any use of the can cell. possible return values: can_init_failure and can_init_success. comments calls can_init() (see section 3.2.2 "internal routines" ) input -- output -- description disables all can interrupts. comments -- input -- output current status of the cell description retrieves the current status of the can cell. possible return values: can_standby, can_bus_passive, can_bus_off and can_bus_active following the current state of the cell. comments useful if the status_change_notification option is enabled in can_custom.h input -- output value of the tecr register (transmission error counter) description returns the value of the tecr comments -- input -- output value of the recr register (reception error counter) description returns the value of the recr comments -- input chip wake-up function: bus_wakeup or soft_w akeup output error status
23/100 st7 pcan peripheral driver can_switch_error can_sleep (wakeup_cause): can_switch_error can_switch_on(init_data_ptr,can_bool): can_transmit_error can_transmit_request(can_buffer*): description puts the can node into standby state. this function aborts any pending transmissions and does not wait for the reception buffers to be read. then, it resets the driver in the same state as after power-on ini- tialization. if bus_wakeup is selected, the next dominant bit detected on the bus will restart the cell. if soft_wakeup is selected, the cell w ill not take the bus state into ac- count. it can only be woken up by the can_switch_on function. possible return value: can_sleep_success or can_fatal_error (if the run bit fails to reset after a time out or if the can_clean function fails). there is a time out mechanism implemented in this function (about 30ms), waiting for the run bit to be actually reset. so if your application uses the watchdog refresh it before calling the function comments calls can_clean (see section 3.2.2 "internal routines" .) input chip wake-up function: bus_wakeup or soft_wakeup output error status description puts the can node into standby state. returns can_sleep_error if a transmission re quest is pending, or if a hardware reception buffer is still unsaved. possible return values: can_sleep_error if there are jobs pending in the hardware registers, can_fatal_error if the run bit fails to reset after a time out, or can_sleep_success comments this function will not reset the can node. input pointer on an init_data structure (see section 2.1.5.1 "data-type variables" ), boolean (ctrue, cfalse) output error status description puts the can node into active state the boolean is used to transmit a dominant pulse (ctrue) or not (cfalse) upon wake-up. the bit timing and the mask/filter parameters can be reinitialized in this function. in most cases, the cell will be initialized the same way as in the power-on sequence. so, you can re-use the first_init_data structure is declared in can.h. possible return values: switch_on_succes and switch_on_failure. comments calls can_init (see section 3.2.2 "internal routines" ). input pointer to the can message to be sent output error status
24/100 st7 pcan peripheral driver 2.1.5.3 constants those constants are defined internally, but are made visible to the user because they may be useful. extern const init_data first_init_data this is the initialization data structure that is used on power-on. it is made visible to allow you to pass it to the can_switch_on function when you do not want to modify the parameters it contains. (see section 2.1.5.1 "data-type variables" ) extern const u16 i_filters[]; this is the array of filters used to perform software filtering on incoming messages. the max- imum number of identifiers stored is 127 (see filtering on page 29 ). it is made visible in case you would like to link the behaviour of your application upon reception of a message with the offset of the identifier in the array (managing an array of pointers to functions for example). one can of course imagine other applications. 2.1.5.4 can_custom.h file the preprocessor directives used to configure the hardware and to customize the driver are located in this file. cell configuration values #define init_brpr 0x00 #define init_btr 0x00 these values are used to initialize bit timing registers. (see section 2.2.2.1 "bit timing" ). /*masks & filters*/ #define init_fhr0 0x00 description puts a buffer into the transmission queue, and may request an immediate transmis- sion if the queue is empty. the buffer_rw field has to be cfalse before passing it to the function. it is immedi- ately marked as ctrue after entering the routine. in case of an error, during the ex- ecution, this parameter is reset to cfalse before exiting. else it is only reset by can_fill_transmission_buffer (see section 3.2.2 "internal routines" ). possible return values: can_transmit_failure if the cell is in stand-by, can_fifo_full if the 3 messages deep fifo is full, can_transmit_fatal if can_fill_transmission_buffer fails, or can_transmit_success otherwise. comments this function must not be interrupted, so protect it with sim and rim statements when used outside the notification functions of can_custom.c! calls can_init_queue and can_fill_transmission_buffer (see section 3.2.2 "inter- nal routines" )
25/100 st7 pcan peripheral driver #define init_flr0 0x00 #define init_mhr0 0x00 #define init_mlr0 0x00 #define init_fhr1 0x00 #define init_flr1 0x00 #define init_mhr1 0x00 #define init_mlr1 0x00 these values are used to initialize hardware filters and masks. (see filtering on page 29 ). compilation options //start options //#define wake_up_pulse #define run_on_start_up you may decide whether or not to include these options in the code. if enabled: C wake_up_pulse enables the cell to send a dominant bit when leaving standby mode. C run_on_start_up starts the cell in the initialization function can_first_init. if not en- abled, make sure that a dominant bit detected on the bus can make the cell start. to do this, complete the can_dominant_bit_reception_notification() function in can_custom.c in calling can_switch_on. //#define filters_enabled //#define init_filters {} these options are used for software filtering. select both of them if you want to use the feature. if selected, enter the list of identifiers to be accepted between the curly braces as shown in software filter configuration on page 30 . enabling one of the following options implies modifying the corresponding function in the can_custom.c file: //#define status_change_notification this option is used to monitor status changes (active/passive/bus-off). setting this option will change the priority order in which the interrupts are taken into account. the interrupts con- cerning status change will be checked first, before considering reception and transmission in- terrupts. it will also allow compilation of the corresponding notification functions (can_bus_passive_notification, can_bus_active_notification, can_bus_off_notification). to use the error notification functions (called when an error it is received), enable: //#define debug
26/100 st7 pcan peripheral driver if debug is defined, you can then chose to add the following options: //#define general_reception_error all reception errors trigger an interrupt. you cannot use this option and the status change notification function together because both use the same it flag. this option does not exclude the bus wake-up feature. //#define simultaneous_emission_reception only if debug is also defined. this function is used for forcing the cell to simultaneously send and receive any message it is ordered to transmit to check the hardware integrity of the can transceiver and controller. 2.1.5.5 can_custom.c file this is a source file you have to complete, to allow your application to react on hardware events as they happen. an example of implementation is given in section 2.2.3 "implementing the notification functions" . functions called unconditionally can_buffer* can_request_buffer(u16 ident_of_message) this function is called unconditionally when a new data message is available in the hardware buffer of the cell. this function has to be completed to return a pointer on a buffer structure. to ignore it, return null. to help you to manage your reception buffer(s), the id of the message is passed as a parameter. void can_remote_reception_notification(u16 ident_of_remote) this function is called unconditionally when a remote message has been saved in a hardware buffer. its id is passed as a parameter for a quick answer. void can_data_reception_notification(u16 message_ident) this function is called unconditionally when a data message has been successfully saved in a software buffer supplied by the application. its id is passed as a parameter. void can_transmission_notification(void) this function is called unconditionally upon the successful transmission of a message. functions called conditionally the following functions are called only if the corresponding option is set in can_custom.h. void can_dominant_bit_reception_notification(void) this function is called upon reception of a dominant bit while in standby mode, if the run_on_startup option was not defined in can_custom.h. the corresponding interrupt will be accepted only once. then its acceptance flag will be cleared. void can_bus_passive_notification(void) void can_bus_active_notification(void)
27/100 st7 pcan peripheral driver void can_bus_off_notification(void) these functions are called after a status change. option: #define status_change_notification void can_general_reception_error_notification(void) this function notifies the application of any hardware reception errors. option: #define debug and #define general_reception_error void can_reception_status(can_receive_error status) this function is called after a reception attempt and returns the status of the software processing (see enum -type variables on page 20 ). option: #define debug void can_overrun_notification(void) this function notifies the application of any overruns. option: #define debug void can_transmission_error_notification(can_transmit_error status) this function notifies the application of any hardware transmission errors. option: #define debug 2.2 how to use the can driver: a demo application in this section, we will describe step-by-step the configuration and programming of a simple test application using the st7 can driver. 2.2.1 application first of all, we must define how the application will look, i.e. which messages our cell will be able to send, which ones it will accept to receive, and how it will behave when specific mes- sages are received. lets imagine the following: C the cell has to run immediately after power-on, and does not have to send a dominant pulse. C every 15 ms the cell must send the contents of the st7 a/d converter data register. the identifier (id) of this message could be, for example, 0x402. C upon reception of a remote frame (see section 1.2 "can frame" ) it must reply with the trans- mission of a given message. the id of the remote frame could be, for example, 0x500 (con- sequently, the id of the answer will also be 0x500). C upon reception of a given data item, the can cell must shut down. this id of the message could be 0x600, and the data item 0xff, in its first data byte. C the cell is supposed to receive 3 other data messages coming from other nodes. lets im- agine they are identified by 0x127, 0x311, 0x3a5.
28/100 st7 pcan peripheral driver C identifiers may exist on the bus that do not concern our cell. 2.2.2 cell configuration open then the can_custom.h file. you can see the two first lines of code: //#define wake_up_pulse //#define run_on_start_up according to our requirements (see section 2.2.1 "application" ), we only want to define the run_on_startup option. so modify the code the following way: //#define wake_up_pulse #define run_on_start_up 2.2.2.1 bit timing first of all, we have to decide the speed of our network. lets say, for example, 250 kilobaud. look in your can_custom.h file. you see the following code: #define init_brpr 0x00 #define init_btr 0x00 the following two registers define the bit timing in the cell. the brpr register contains the size of time quantum, in number of clock ticks, in a bit field named brp (see section 1.3.2 "bit timing" ).this field ranges from 0 to 63. the true value for a time quanta is then brpr+1. the btr register contains the size of the two synchronization segments in time quanta, in two different bit fields: bs1 and bs2(). bs1 ranges from 0 to 7and bs2 from 0 to 3. the actual length of bit segments in time quanta is then bs1+1 and bs2+1. you must always chose bs1>bs2, so that the sampling point takes place in the second half of the bit. use the following formula: for example, in our case, fcpu = 8 mhz. so, fbus = fcpu/32. we have then the following possibilities: btr+1 bs1+bs2+3 216 fbus bauds () fcpu hz () 1 brp + () 3 bs 1 bs 2 ++ () ------------------------------------------------------------------------- =
29/100 st7 pcan peripheral driver lets choose, for example, btr = 3, bs1 = 3, bs2 = 2 (second row). we have to complete the code: #define init_brpr 0x03 #define init_btr 0x23 2.2.2.2 filtering the driver is able to filter out all messages not needed by the application. first by using hard- ware filters, and second by using software filters. use the hardware filters to eliminate as many identifiers as possible and to avoid further processing. use the software filters to eliminate ids that are unwanted, but that can not stopped by the hardware. hardware filter configuration lets define the values of hardware masks and filters. to do this, we must split the ids into two groups: C 0x127, 0x311 and 0x3a5, on one hand; and, C 0x500 and 0x600 on the other. note : when grouping the ids, try to maximize the number of identical bits inside the same group, thus minimizing the width of the id ranges accepted by the cell. then lets find the first filter/mask pair (12 bits to be determined): C 0x500 is written in binary: 101 0000 0000 C 0x600 is written in binary: 110 0000 0000 in the first three bits, only the most significant bit (msb) of both identifiers is the same, the fol- lowing two being different. so, the three msbs of the mask will be 1 0 0 (match, dont care, dont care) and the three msbs of the filter will be 1 and then either 1 or 0. the following eight bits are identically null. so the last eight bits of the filter will be 0, and the last eight bits of the mask will be 1 (match required). the least significant bit (lsb) of the filter/mask is used to separate remote frames and data frames. here we have a data frame and a remote frame, so it does not have to be checked (1 or 0 into the filter, 0 into the mask). so we have: C filter 1000 0000 0000 C mask 1001 1111 1110 48 84 btr+1 bs1+bs2+3
30/100 st7 pcan peripheral driver now look at the can_custom.h file: there are several #define statements, including: #define init_fhri 0x00 #define init_flri 0x00 where i is either 0 or 1. these are the two registers containing hardware filters. in the fhri register, the 8 msbs for the filters are given, and in the second register the 4 lsbs are given followed by 4 zeros. we have to do the same thing for the mask. first, lets write 0 for the filter. finally we have: #define init_fhr0 0x80 #define init_flr0 0x00 #define init_mhr0 0x9f #define init_mlr0 0xe0 doing the same thing with the other group of identifiers leads to: #define init_fhr1 0x20 #define init_flr1 0x20 #define init_mhr1 0xa9 #define init_mlr1 0x30 software filter configuration you need to use software filtering feature if the hardware cannot stop all the undesired identi- fiers. look at the following code in can_custom.h: //software acceptance masks //#define filters_enabled //#define init_filters {} to allow software filtering, remove the // comment signs, and enter the identifiers between the parentheses. please note that the filters must be given in hexadecimal format with four digits , always terminated by zero , and in increasing order . that is to say in our case: software acceptance masks: optional choice #define filters_enabled #define init_filters {0x1270,0x3110,0x3a50,0x5000,0x6000} note : there can not be more than 127 identifiers in the array. 2.2.3 implementing the notification functions the cell is now configured, we no longer need to worry about hardware.
31/100 st7 pcan peripheral driver we have then to write our code. look at the last lines of can_custom.h. there is a set of #de- fine options. as we want to be notified neither of status changes, nor of errors, we will leave them as comments. please see section 2.1.5.5 "can_custom.c file" for more details about notification functions. we must then open can_custom.c, and learn how to use the notification functions that are al- ways compiled. if your application uses the watchdog timer, you have to write on top of the file: #include wdg.h to be able to use the refresh function in this module. the can_request_buffer function to retrieve data stored in the st7 buffers after reception, the application must pass a software buffer when requested. the following prototype is given in the code: can_buffer* can_request_buffer(u16 ident_of_message) { //the application must here return a pointer to a physical structure can_buffer } this routine is called each time a message has been successfully filtered and is ready to be used. the parameter passed (i.e. the id of the recovered message) may help you manage your buffer(s) more easily. you then have to create a buffer that will be used to save all data messages. at the top of the file, add: //////////////////////////////////////// //variables///////////////////////////// //////////////////////////////////////// can_buffer reception_buffer; and then in the function body: can_buffer* can_request_buffer(u16 ident_of_message) { reception_buffer.buffer_rw=ctrue; return &reception_buffer; } the two first lines are used as a safety device: the driver will then be sure that the buffer is not currently in use and the data in that buffer can be overwritten. in your programs, use these fields as keys to know whether the data in a buffer can be accessed and whether it has already been processed. note 1 : there is only one buffer here that will be used to save all the receive messages. this is only an
32/100 st7 pcan peripheral driver example! you can implement a buffer for each message type, a fifo of standardized buffers etc. note 2 : for safe programming, you should systematically verify whether the buffer is not currently being read/written, and whether the buffer is really free before further processing. (for specific information concerning the buffer data type, see section 2.1.5.1 "data-type var- iables" ). remember that one of the received messages may switch off the cell. once a message is re- ceived, we have to check to see if it is this one. this is done using the can_data_reception_notification function. can_data_reception_notification function the can_data_reception_notification function is the following prototype in can_custom.c. the routine is called once the data in a data frame has been saved in the buffer passed in the can_request_buffer function. before calling the can_switch_on function, refresh the watchdog (see functions on page 21 , can_switch_off for further explanation). lets add the following code: void can_data_reception_notification(u16 message_ident) { if (message_ident==0x6000)//checks the id of message { if (reception_buffer.can_msg_data[0]==0xff)//checks the content of data { can_switch_off(bus_wakeup); } } } so, if the first data byte of the message whose identifier is 0x600 contains 0xff, the cell will switch off and wait for a bus wake-up command (a dominant bit). can_remote_reception_notification function when a remote frame is received, we must send a message with a 0x500 id. lets do it inside this routine which is called each time a remote frame is received. the message does not exist yet. as for the buffer, we have to create a variable message , by adding the following code in the file: //////////////////////////////////////// //variables///////////////////////////// //////////////////////////////////////// can_buffer message_to_send_on_request= / {0x5000,dlc5,{0x00,0x01,0x02,0x03,0x04},cfalse,cfalse};
33/100 st7 pcan peripheral driver the structure is initialized here with 0x500 id, which has a length of five and five data items. note : in a real network, the message would not be statically initialized, but would be filled with the content of one or several variables. the aim here is only to show the way the function can be used. then we fill the function with a transmission request: void can_remote_reception_notification(u16 ident_of_remote) { if (ident_of_remote==0x5000) { can_transmit_request(&message_to_send_on_request); } } can_transmission_notification function this function is called after each successful transmission. it is not required for our application, so lets leave it blank. can_dominant_bit_reception_notification function this function is called each time a dominant bit is received while in standby mode. here, we want to be able to wake up the cell when this happens. so we add the following code: void can_dominant_bit_reception_notification(void) { can_switch_on(&first_init_data,cfalse); } the cell will be woken-up with the same configuration as when first initialized and a dominant pulse will not be sent at wake-up. note : for the exact meaning of the data parameters, see section 2.1.5.2 "functions" all other notification functions can be used in the same way. they are compiled only if the cor- responding options are chosen in can_custom.h. 2.2.4 transmissions outside the can interrupt function as part of the user interface, the can_transmit_request routine can be used outside the in- terrupt function of the can driver. below is an example of a message transmission on a timer event. the content of the a/d converter of the st7 microcontroller will be sent every 15 ms. first of all, we must configure the timer by modifying the existing code. at the top of the tima.c file, add: #include can.h #include lib.h #include adc.h then declare a can_message -type variable:
34/100 st7 pcan peripheral driver can_buffer periodic_transmission; in the tima_init() function, make sure the following lines are included: tacr1=0x40 tacr2=0x08 taoc1hr=0x3a taoc1lr=0x98 and finally, #asm ld _taoc2hr,a; /* write the output compare 2 high register to disable the oc2 */ ld a,_tasr /* clear the flags in case it is already set. to clear */ ld a,_taoc1lr /* oc1f flag: read status register and access oc1r low byte, clearing oc1f flag */ ld a,_taoc2lr /* oc2f flag: read status register and access oc2r low byte,clearing oc2f flag*/ ld _taoc2hr,a//no access to low byte: outputcompare 2 its disabled #endasm note : the explanation of the code written here concerns timer programming and is beyond the scope of this document. its purpose is to configure timer a to trigger a timer interrupt every 15 ms. further explanations of timer functions can be found in the microcontroller datasheet. then we have to fill in the it function of the timer: void tima_interrupt(void) { u16 output_value; if (valbit(tasr,ocf1)) { tasr; output_value = ((unsigned int)taoc1hr << 8)| taoc1lr; } output_value += 0x3a98; taoc1hr = output_value >>8; taoc1lr = (unsigned char) output_value; //note: the code above is only meant to update the value for the next it //now comes the code that interests us if (!periodic_transmission.message_in_queue) //checks if the message is already //in the transmission queue { periodic_transmission.msg_identifier=0x4020; periodic_transmission.data_size=dlc1; periodic_transmission.can_msg_data[0]=adc_get(0x00);
35/100 st7 pcan peripheral driver can_transmit_request(&periodic_transmission); } //we have given a transmission order here, that will be called on every //timer it if the message is not already in the transmission queue. //the data is filled each time with the value of the a/d converter data //register. for info. about the adc, please see the datasheet. } important : please note that when used outside an interrupt routine, and only then, the transmission request must not be interrupted. so, disable all its before a function call (sim) and re-enable them afterwards (rim) in the last step of the main.c file. in the adc.c file, enter also the following code: in the adc_init routine: adccsr=0x20;//starts the adc peripheral and write a function: u8 adc_get(u8 channel) { adccsr |= channel; return adcdr; } our application is almost entirely written now. our last step is to fill the main.c file, to allow the entire program to run. at the beginning of the file add: #include lib.h #include adc.h #include tima.h #include can.h #include can_custom.h then complete the main function as follows: void main(void) { _asm(sim); //disable interrupts /* ----------------------------- */ /*------------------- i n i t i a l i s a t i o n -------------------------*/ /* ----------------------------- */
36/100 st7 pcan peripheral driver adc_init(); //initializes the adc if ((can_first_init())==can_init_failure) //initializes the can peripheral { return; } tima_init();//initializes the timer _ asm(rim);// enableinterrupts; /* ------------------- */ /*---------------------------- loop --------------------------*/ while (1) /* ------------------- */ { } } finished! now compile the entire code and run the software. once the while {1} loop is en- tered, the microcontroller will run non-stop until it is shut down, reacting to every event, saving data in our buffer, sending data periodically and answering remote requests. if you own a can bus simulation tool, you can monitor messages being received and sent by the st7. the next section of this application note will explain in detail the driver architecture and all soft- ware functions (including internal functions). 2.2.5 important: reentrant functions if the memory model you chose for compiling your application does not use the physical stack but simulates it in ram, you cannot allow functions to be reentrant. the cosmic compiler will generate an error if it finds some code that could be reentrant. for example, this may occur if you use a subroutine inside both an initialization function and an in- terrupt routine. this is, of course, not a real error, but the compiler does not know this and prevents you from going further. to fix this problem with the cosmic compiler, use the following trick: C change the name of the function in your code, in the call that makes the error appear.
37/100 st7 pcan peripheral driver C for example, rename function to function_init_call . C in the link file (extension .lkf), define an alias the following way: +def _function=_function_init_call //!! note the underscore as first character. C if the function takes parameters, add also: +def _function$l=_function_init_call$l//!! this is the way the parameters names are generated by the compiler C save the file and compile. in any case, always make sure that your code is not actually reen- trant, if it is, it wont run the way you expect, even if you have compiled it sucessfully!
38/100 st7 pcan peripheral driver 3 detailed description in the following section we will give a detailed description of function algorithms. we will also look at the internal aspects of the driver. 3.1 user interface functions as described above in the routine parameters and return values, the algorithm will only be shown on flowcharts. for more information, refer to section 2.1.5.2 "functions" . void can_it_dis(void): simply clears the can interrupt control register. u8 can_get_tec(void): simply returns the value of tec. u8 can_get_rec(void): simply returns the value of rec. can_init_error can_first_init(void) figure 13. can_first_init flowchart run=0 y n begin y returns can_init_failure initializes transmission queue locks buffer 1 calls can_init returns can_init_success success?
39/100 st7 pcan peripheral driver can_status can_get_status (void) figure 14. can_get_status flowchart can_switch_error can_switch_off(wakeup_cause) figure 15. can_switch_off flowchart can_switch_error can_sleep (wakeup_cause) run=0 epsv=1 boff=1 yyy nnn begin returns can_bus_active returns can_bus_off returns can_bus_passive returns can_standby y n begin success ? y run = 0 counter = 0 n y n returns can_sleep_success decrements counter returns can_sleep_fatal calls can_clean modifies canicr register following the parameter (enables or disables it) sets run = 0 sets counter = 0xfff
40/100 st7 pcan peripheral driver figure 16. can_sleep flowchart can_switch_error can_switch_on(init_data_ptr,can_bool) figure 17. can_switch_on flowchart can_transmit_error can_transmit_request(can_message*) y status_counter=0 n y n begin n run = 0 y y n returns can_sleep_error returns can_sleep_fatal returns can_sleep_success modifies canicr register following the parameter (enables or disables it) unlocks buffers 1 and 2 sets run = 0 locks it hardware buffer 3 is empty hardware buffer 2 is empty locks it begin run = 0 y n success ? y n returns can_switch_on_failure returns can_switch_on_success calls can_init cancels any pending job (clears lock bit)
41/100 st7 pcan peripheral driver figure 18. can_transmit_request flowchart 3.2 internal functions and data types 3.2.1 internal data types and variables 3.2.1.1 transmission fifo to avoid losing data, messages to be sent are queued in a 3-message length fifo prior to transmission. queue unit in fact, no physical can_message structure is put into the queue. the objects handled are de- scribed below: typedef struct fifo_object { can_message* message; struct fifo_object* next_object; struct fifo_object* preceding_object; }fifo_object; only a pointer to the message appears in the structure, to avoid complex data manipulations. the two following fields are pointers to other fifo_object structures. y y n n run = 0 begin fifo full? no message? y n message_to_send.buffer_rw=ctrue message_to_send.buffer_rw=cfalse returns can_transmit_failure returns can_fifo_full message_to_send.buffer_rw=cfalse returns can_transmit_fatal returns status (result of can_fill_transmission_buffer) can_fill_transmission_buffer message_to_send.buffer_rw=cfalse can_in_queue (msg_to_send)
42/100 st7 pcan peripheral driver fifo management structure in the main structure, we find: typedef struct { u8 fifo_size; fifo_object* first_object; fifo_object* last_object; can_bool isinuse; } fifo; the structures shown here look more like parts of a chained-list. indeed, the data-type imple- mented is not pure fifo, but simulates the behaviour of a real queue. three fifo_objects are statically defined and linked together in a circular way (in the can_first_init routine). one fifo variable is also defined and initialized in the meantime (cf. in can.c): //transmission queue static fifo can_transmit_queue; static fifo_object can_queue_object_1; static fifo_object can_queue_object_2; static fifo_object can_queue_object_3; the maximum size of the queue is therefore 3. to simulate in-queuing/out-queuing, you only have to verify that the size limit will not be over- ridden, and update the fields in the fifo structure. the isinuse boolean is checked each time the variable is accessed to prevent read/write conflicts.
43/100 st7 pcan peripheral driver figure 19. fifo transmission system for more information, refer to section 3.2.2 "internal routines" , (can_in_queue and can_out_queue). 3.2.1.2 software filters once the software_filters option is defined in can_custom.h and the list of filters is completed, the compiler will define and initialize a structure containing the data. typedef struct{ u8 array_size; u16* filters_array; }can_filters_array; this structure is composed of the size of the array, automatically calculated at compilation, and of an array of 2-byte long numbers. consequently, the following constants are defined in the can.c file: const u16 i_filters[]=init_filters; const can_filters_array can_filters={ size_of_words_array(i_filters), i_filters }; as we can see, they are immediately initialized. size_of_words_array is a macro and i_filters is the array filled with your data. you can access the i_filters array, declared as extern const in can.h. 3.2.1.3 enum types they are used as return values for some internal routines. object 1 object 2 object 3 fifo management next next next preceding preceding preceding 1st object last object in use? current size = xx & message & message & message next data to send
44/100 st7 pcan peripheral driver typedef enum {can_filter_match,can_filter_no_match}can_filter_status; return values of the software filtering routine. typedef enum {iterr,itrecept,ittransmit,itscif}it_type; return values of the routine that determines which it has to be processed first. typedef enum {can_clean_fatal,can_clean_success,can_clean_failure}can_clean_error; return values of the cleaning function. 3.2.1.4 status counter static u8 status_counter=0; this is a variable used by the sleep function to determine the state of the reception and trans- mission registers. it is updated the following way: C +1, when a reception it is taken into account C -1, when a reception buffer is released C +1, when a message is put into the transmission queue C -1, when a message is sent (in the it function) when the can_sleep function is called, a simple test of this variable lets the driver know if there are still pending jobs and if the sleep operation must be cancelled. 3.2.2 internal routines 3.2.2.1 static can_filter_status can_filter(u16 ident_code) performs a classical dichotomy algorithm and compares the value given as parameter with the contents of the i_filters array . input can message identifier output error status description tests matching of ids of received messages and software filters. possible returned status: can_filter_match and can_filter_no_match comments called by can_receive compiled only if filters_enabled is set. p riority is given here to speed, thats why the code may look strange.
45/100 st7 pcan peripheral driver 3.2.2.2 static it_type can_get_it_type(void) figure 20. can_get_it_type flowchart input -- output generic type of the event that caused the it description tests matching of ids of received messages and software filters. if the debug option is defined, checks the it error flags first. otherwise checks the reception its first. possible status returned: itrecept for reception it, ittransmit for transmission it and iterr for error it. comments called by can_interrupt. begin (case debug) y epnd=1 n n scif=1 txif=1 rxifi=1 n y y y begin (case no debug) scif=1 if status_ change_notification txif=1 rxifi=1 scif=1 change_notification if not status_ returns ittransmit returns itrecept returns itscif returns iterr
46/100 st7 pcan peripheral driver 3.2.2.3 static can_init_error can_init(init_data_ptr data_ptr, can_bool run_set, can_bool wkup_set) figure 21. can_init flowchart input pointer to an init_data structure, boolean, boolean output error status description can cell internal registers initialization. not executed if run bit set. the first boolean determines if the run bit has to be set or not. the second boolean determines if the cell has to send a wake-up dominant bit. possible status returned: can_init_failure and can_init_success comments called by can_switch_on, can_first_init n begin run=1 y returns can_init_failure writes timing registers writes interrupt control register writes filters/masks writes control status register returns can_init_success
47/100 st7 pcan peripheral driver 3.2.2.4 static can_transmit_error can_in_queue (can_message* msg_to_queue) figure 22. can_in_queue flowchart input pointer on a can message output error code description tests matching of ids of received messages and software filters. possible return values: can_fifo_full, can_transmit_success and can_transmit_fatal. comments must not be interrupted called by can_transmit_request n begin y queue in use fifo full n y returns can_transmit_fatal returns can_fifo_full returns can_transmit_success unlocks queue unlocks queue locks queue updates fifo parameters
48/100 st7 pcan peripheral driver 3.2.2.5 static can_message* can_out_queue (void) the algorithm is exactly the same as for can_in_queue(). 3.2.2.6 static can_clean_error can_clean (void) figure 23. can_clean flowchart input -- output pointer to a can message description returns a pointer to the first message in the transmission queue and updates the queue parameters comments must not be interrupted called by can_fill_transmission_buffer input -- output error status description cleans the reception and transmission buffers, and resets the transmission queue in the first initialization state. only affects pointers possible return values: can_clean_failure, can_clean_success and can_clean_fatal comments must be called only in sleep mode (run bit reset) must not be interrupted called by can_sleep and can_switch_off n begin run=1 y queue in use y n returns can_clean_fatal returns can_clean_failure returns can_clean_success locks queue reinitializes queue clears all pending jobs clears all pending its unlocks queue
49/100 st7 pcan peripheral driver 3.2.2.7 static can_transmit_error can_fill_transmission_buffer() figure 24. can_fill_transmission_buffer flowchart input -- output error status description fills the hardware buffer for transmission. possible return values: can_transmit_buffer_full, can_transmit_no_msg and can_transmit_success comments its have to be disabled called by can_transmit_request calls can_out_queue n begin y rdy=1 message exists n y i.e. not null selects buffer 1 can_out_queue() returns can_transmit_no_msg returns can_transmit_buffer_full returns can_transmit_success fill the hardware buffer message.buffer_rw=cfalse
50/100 st7 pcan peripheral driver 3.2.2.8 static can_receive_error can_store_rcvd_msg(u8 num_buff_hard, can_recept_buffer* dest_ptr) figure 25. can_store_rcvd_msg flowchart input number of the hardware buffer to release, pointer to the buffer where the data must be saved output error status description fetches data received in a hardware buffer. possible return values: can_illegal_identifier and can_receive_success comments its have to be disabled. this function is called by can_reception, only in case of reception of data. the priority was given to speed here, that` s why the code may look strange. n begin y legal value i.e. <9 retrieves data length returns can_illegal_identifier returns can_receive_success saves data in the software buffer releases the hardware buffer, therefore clearing the it flag
51/100 st7 pcan peripheral driver 3.2.2.9 static can_receive_error can_receive(u8 num_buff_hard) figure 26. can receive flowchart input id of the buffer to void, pointer on the software buffer to fill. output error status description fetches data received in a hardware buffer and saves them in a software buffer sup- plied by the application . comments its have to be disabled calls can_filter (if software_filter option is enabled) calls can_request_buffer possible return values: can_filtering_failure,.can_receive_remote, can_no_buffer, can_receive_fatal and can_receive_success n begin filter_match if software_filters defined y remote frame? y n buffer exists? y n buffer already y n accessed? buffer free? y n status=success y n retrieves message identifier can_filter() releases hardware buffer calls can_remote_reception_notification() calls can_filtering_failure returns can_receive_remote returns can_no_buffer returns can_receive_fatal releases hardware buffer releases hardware buffer releases hardware buffer releases hardware buffer calls can_request_buffer() calls can_data_reception_notification() returns can_receive_success can-store_received_message
52/100 st7 pcan peripheral driver 3.2.2.10 interrupt routine figure 27. interrupt routine flowchart input -- output -- description interrupt processing function. comments calls can_get_it_type can_reception_notification can_transmission_notification can_fill_transmission_buffer can_dominant_bit_reception_notification may call (optional, see section 2.1.5.4 "can_custom.h file" ): can_transmission_error_notification can_bus_passive_notification can_bus_active_notification can_bus_off_notification can_overrun_notification can_general_reception_error_notification begin y n case: itrecept buffer 3 filled buffer 2 filled if debug defined n y switch: get_it_type() break break same processing as buffer 3 can_reception_status can_receive
53/100 st7 pcan peripheral driver continued case: ittransmit if debug defined case: itscif status = standby if status_change_notification defined case: can_bus_passive case: can_bus_active case: can_bus_off if general_reception_error defined y n clears interrupt flag can_fill_transmission_buffer() can_transmission_error_notification() break if status_change_notification defined or run_on_startup not defined can_transmission_notification() can_dominant_bit_reception_notification () switch: can_general_reception_error _notification() break can_bus_off_notification() can_bus_active_notification() can_bus_passive_notification() remove it authorisation clears interrupt flag can_get_status()
54/100 st7 pcan peripheral driver continued if debug defined case: iterr orif it n teif it y y n can_overrun_notification() can_transmission_error_notification() clears interrupt flag break clears interrupt flag
55/100 st7 pcan peripheral driver 3.3 a few words about driver performance 3.3.1 cpu load lets imagine the following situation: C bus rate: 100 kilobauds C bus load: 80% C f cpu : 8 mhz C 14 identifiers (typical value) have to be received. lets measure the time spent inside the interrupt function when a message is received. the application processing inside the notification functions must be minimal: they only return a buffer to be filled. we retrieve the following results: C 8 bytes data message, filter match: 105 s C 0 bytes data message, filter match: 90 s C any message, filter no match: 50 s note : any message, if only the eight most significant bits match, takes 100 s. that is to say almost as much time as with matching identifier. so it is better to chose the identifiers wisely, in order to prevent this from occurring as much as possible. the longest possible message (2.0a standard) is 130 bits long (including stuffing bits). im- agine that all messages on the bus are that long. consequently, there will be 615 messages per second on the bus, thats to say one message every 1.625 s. the saving of data lasts 105 s, so the cpu load is in this case 6.5%. the same calculation for 0-byte messages (shortest possible) leads us to 15.3% cpu load. note that these are worst case scenarios! not all the messages on the bus have to be saved. and the bus load chosen here is pretty heavy (typical values are rather around 40%). do not forget to multiply or divide these values if you want an estimation of cpu load under other bus speed/bus loading conditions and other f cpu speeds.
56/100 st7 pcan peripheral driver 3.3.2 code size the numbers given here correspond to the size of the driver code without any addition of application specific code. 3.3.2.1 can.o module table 2. can.o code size 3.3.2.2 can_custom.o module table 3. can_custom.o code size rom ram (page 0) ram (default) functions 1326 bytes -- -- variables & constants 10 bytes 19 bytes (shared segment) 28 bytes rom ram (page 0) ram (default) functions 5 bytes -- -- variables & constants -- -- --
57/100 st7 pcan peripheral driver 4 driver code 4.1 can.c /*********************** (c) 2000 stmicroelectronics ************************* project : compiler : st7 cosmic c v4.2e module : can.c version : v 1.1.6 build 80 creation date : 04/00 author : central europe 8bit micro application group -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- description : can routines -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- modifications : rim statement removed from interrupt routine (1.0.0) transmission and reception structures merged into one "buffer type"(1.1.1) management of semaphores (buffer_rw and buffer_free)slightly modified(1.1.2) updated to comply with st7ap_ii (1.1.2 build 80) it management slightly modified (1.1.3) modif. transmission it >> flag reset(1.1.4) bug corrected in can_switch_off(1.1.5) reset of its vector in can_init(1.1.6) **************************************************************************** the software included in this file is for guidance only. st microelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from use of this software. ***************************************************************************/ #include "lib.h" #include "can.h" #include "can_hr.h" #include "can_custom.h"
58/100 st7 pcan peripheral driver //compilation options coherence check #ifndef debug #ifdef general_reception_error #error "debug not defined in can_custom.h" #endif #ifdef simultaneous_emission_reception #error "debug not defined in can_custom.h" #endif #endif #ifdef general_reception_error #ifdef status_change_notification #error "general_reception_error and status_change_notification incompatibles in can_custom.h" #endif #endif / *#########################################################################*/ /* constants alias */ / *#########################################################################*/ #define page_1 1 /* */ #define page_2 2 /* can */ #define page_3 3 /* pages */ #define page_filters 4 /* */ #define reception_2 2 /*receptions buffers*/ #define reception_3 3 #define max_fifo_size 3 /*size of the emission fifo*/ #define recept_mask 0xc0 /*masks */ #define transmit_mask 0x10 /*to retrieve specific*/ #define scif_mask 0x08 /*it flags */ #define error_mask 0x01 #define filter_shift 1 /*shift applied to the identifiers managed by software
59/100 st7 pcan peripheral driver */ // to give them the correct hardware format #define remote_bit 5 /*place of the remote bit in the id field*/ #define register_size 8 /*size of a register*/ / *#########################################################################*/ /* structures typedef */ / *#########################################################################*/ //transmission queue element typedef struct fifo_object{ // definition of the reception fifo unit can_buffer* message; // pointer to a can message structure struct fifo_object* next_object; // pointer to the following object in the queue struct fifo_object* preceding_object; // pointer on the preceding object in the queue }fifo_object; // //transmission queue typedef struct { // definition of the reception fifo type u8 fifo_size; // size of the fifo fifo_object* first_object; // next object to be outqueued fifo_object* last_object; // next place to fill can_bool isinuse; // data sharing control } fifo; #ifdef filters_enabled //filtering results typedef enum {can_filter_match,can_filter_no_match}can_filter_status; #endif //it types typedef enum {iterr,itrecept,ittransmit,itscif}it_type; //clean error codes typedef enum {can_clean_fatal,can_clean_success,can_clean_failure}can_clean_error; / *#########################################################################*/ /* variables */
60/100 st7 pcan peripheral driver / *#########################################################################*/ //static variables //transmission queue static fifo can_transmit_queue; static fifo_object can_queue_object_1; static fifo_object can_queue_object_2; static fifo_object can_queue_object_3; volatile static u8 status_counter=0; //this counter is used by the sleep func- tion to determine the state //of the reception and emission reg- isters //it is used the following way : //+1 when a reception it is taken into account //-1 when a received buffer is released //+1 when a message is put into emission queue //-1 when a message is sent (in the it function) //this is not a shared data, so no particular protection / *#########################################################################*/ /* constantes */ / *#########################################################################*/ #ifdef filters_enabled const u16 i_filters[]=init_filters; // initialization of the filters const u8 can_filters_array_size=size_of_words_array(i_filters); // is defined in can_hr.h // conditionnal compi- lation : only if filters_enabled // the datas are then stored into rom #endif const init_data first_init_data={init_brpr, //that structure is written by the preprocessor
61/100 st7 pcan peripheral driver init_btr, //and stored into rom. it can't be modified then. init_fhr0,//but can be accessed (defined as ex- ternal in can.h) init_flr0, init_mhr0, init_mlr0, init_fhr1, init_flr1, init_mhr1, init_mlr1, }; / *#########################################################################*/ /* functions */ / *#########################################################################*/ //////////////////////////////////////////////////////////////////////////// //notification functions///////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// can_buffer* can_request_buffer(u16); void can_data_reception_notification(u16); void can_remote_reception_notification(u16); void can_transmission_notification(void); void can_dominant_bit_reception_notification(void); #ifdef debug void can_overrun_notification(void); void can_transmission_error_notification(can_transmit_error); void can_reception_status(can_receive_error); #endif #ifdef general_reception_error void can_general_reception_error_notification(void); #endif #ifdef status_change_notification void can_bus_passive_notification(void); void can_bus_active_notification(void);
62/100 st7 pcan peripheral driver void can_bus_off_notification(void); #endif ////////////////////////// //can.c static functions// ////////////////////////// #ifdef filters_enabled /*-------------------------------------------------------------------------- routine name : can_filter input/output : identifier code/error status description : tests matching of ids of received messages and software filters. comments : called by can_recept compiled only if filters_enabled is set. possible returned status : can_filter_match can_filter_no_match --------------------------------------------------------------------------*/ static can_filter_status can_filter(u16 ident_code) { u8 current_first; u8 current_last; u8 current_checked; int current_content; current_first = 0; current_last = can_filters_array_size - 1; for (;;) { current_checked = (u8)(current_first + current_last) >> 1; current_content = i_filters[current_checked] - ident_code; if (current_content < 0) { current_first = current_checked + 1; if (current_first > current_last) break;
63/100 st7 pcan peripheral driver } else if (current_content == 0) return (can_filter_match); else { current_last = current_checked - 1; if (current_last < current_first) break; } } return (can_filter_no_match); } #endif /*ifdef filters_enabled*/ /*-------------------------------------------------------------------------- routine name : can_get_it_type input/output : -- / generic type of the event that caused the it description : it type fetching routine comments : called by can_interrupt possible status returned : itrecept for reception it ittransmit for transmission it iterr for error it --------------------------------------------------------------------------*/ static it_type can_get_it_type(void) { #ifdef debug /*in this case, priority is given to error detection*/ if ((error_mask & canisr)!=0) { return iterr; } else if ((scif_mask & canisr)!=0) { return itscif; } #endif #ifdef satus_change_notification /*in this case, prioity given to status change, eg. to early detect bus-off state*/ #ifndef debug /*if debug is defined, this it has already been taken into account*/
64/100 st7 pcan peripheral driver if ((scif_mask & canisr)!=0) { return itscif; } #endif #endif if ((recept_mask & canisr)!=0) //if not debug, priority is given to recept., then emission, then status-change/wake-up condition// { return itrecept; } else if ((transmit_mask & canisr)!=0) //if not, tests a transmit. it { return ittransmit; } #ifndef debug /*in this case, this it hasn't been tested yet*/ #ifndef satus_change_notification else if ((scif_mask & canisr)!=0) { return itscif; } #endif #endif } /*-------------------------------------------------------------------------- routine name : can_init input/output : pointer on an init structure/error status description : can cell internal registers initialization comments : called by can_switch_on,can_first_init not executed if run bit reset possible status returned : can_init_failure can_init_success --------------------------------------------------------------------------*/ can_init_error can_init(init_data_ptr data_ptr,can_bool run_set,can_bool wkup_set) { if (!valbit(cancsr,run))
65/100 st7 pcan peripheral driver { /*registers init*/ canbrpr=data_ptr->brpr_init;//init of timing variables canbtr=data_ptr->btr_init; //reset canisr register canisr = 0x00; //calculation of the canicr value canicr=0x30; //default value : recept., transmit. #ifdef status_change_notification canicr=canicr|0x08; //a bus wake up may not be wished, but a status change monitoring is wanted #endif #ifdef debug canicr=canicr|0x06; #endif #ifdef general_reception_error canicr=canicr|0x40; //sets the esci bit & the scif bit #endif /*general_reception_error*/ //select filters/masks page canpsr=page_filters; canmlr0=data_ptr->mlr0_init; canmhr0=data_ptr->mhr0_init; canflr0=data_ptr->flr0_init; canfhr0=data_ptr->fhr0_init; canmlr1=data_ptr->mlr1_init; canmhr1=data_ptr->mhr1_init; canflr1=data_ptr->flr1_init; canfhr1=data_ptr->fhr1_init; /*calculation of the cancsr register value*/ cancsr=0x00; if (wkup_set) { setbit(cancsr,wkps); } #ifdef simultaneous_emission_reception
66/100 st7 pcan peripheral driver setbit(cancsr,srte); #endif /*simultaneous_emission_reception*/ if (run_set) { can_run_cell(); } return can_init_success; } else { return can_init_failure; } } /*-------------------------------------------------------------------------- routine name : can_in_queue input/output : pointer on a can buffer output error code description : put a message given by the application into the transmission queue updates the queue parameters comments : called by can_transmit_request must not be interrupted possible return values : can_fifo_full can_transmit_success can_transmit_fatal --------------------------------------------------------------------------*/ static can_transmit_error can_in_queue (can_buffer* msg_to_queue) { if (can_transmit_queue.isinuse) //necessary to avoid multiple simultaneous access { return can_transmit_fatal; //time out ? } //to the datas can_transmit_queue.isinuse=ctrue; //locks the queue if ((can_transmit_queue.fifo_size)>=max_fifo_size) //tests if the fifo is already full { can_transmit_queue.isinuse=cfalse; //if yes, releases the queue return can_fifo_full; //...and aborts process
67/100 st7 pcan peripheral driver } else { //if not, goes on processing can_transmit_queue.last_object=(can_transmit_queue.last_object- >next_object); can_transmit_queue.last_object->message=msg_to_queue; can_transmit_queue.fifo_size=(can_transmit_queue.fifo_size)+1; can_transmit_queue.isinuse=cfalse; return can_transmit_success; //releases the queue } } /*-------------------------------------------------------------------------- routine name : can_out_queue input/output : -- /pointer on a can buffer description : returns a pointer on the first message in the transmission queue. update the queue parameters comments : called by can_transmitrequest must not be interrupted --------------------------------------------------------------------------*/ static can_buffer* can_out_queue (void) { can_buffer* result; if (can_transmit_queue.isinuse) //necessary to avoid multiple simultaneous access { //to the datas return can_transmit_fatal; //can_transmit_fatal=0, that's why the compiler authorises such a return value (<=>null) } can_transmit_queue.isinuse=ctrue; //locks the queue if ((can_transmit_queue.fifo_size)==0) //if the queue is empty { can_transmit_queue.isinuse=cfalse; //releases it return null; } else { //else goes on processing
68/100 st7 pcan peripheral driver result=can_transmit_queue.first_object->message; can_transmit_queue.first_object->message=null; //updates queue parameters can_transmit_queue.first_object=can_transmit_queue.first_object- >next_object; can_transmit_queue.fifo_size=(can_transmit_queue.fifo_size)-1; can_transmit_queue.isinuse=cfalse; //releases the queue return result; } } /*-------------------------------------------------------------------------- routine name : can_clean input/output : -- /error status description : cleans the recept. and emission buffers, and resets the transmis- sion queue. comments : must be called only in sleep mode (run bit reset) must not be interrupted only affects pointers called by can_sleep and can_kill possible return values : can_clean_failure can_clean_success can_clean_fatal --------------------------------------------------------------------------*/ static can_clean_error can_clean (void) { if (!valbit(cancsr,run)) //no cleaning while the can node is running { //cleaning transmission queue if (can_transmit_queue.isinuse) { return can_clean_fatal; } can_transmit_queue.isinuse=ctrue; //locks the queue can_transmit_queue.first_object=&can_queue_object_1; //reinit. the queue can_transmit_queue.last_object=&can_queue_object_3; //(in the same
69/100 st7 pcan peripheral driver state than after 1st. init can_transmit_queue.fifo_size=0; can_queue_object_1.message=null; can_queue_object_2.message=null; can_queue_object_3.message=null; can_transmit_queue.isinuse=cfalse;//releases the queue //hardware cleaning (releases the hardware buffers) canpsr=page_3; while (canpsr>0) { clr_rdy_bit(); canpsr--; } //it cleaning : clears any pending it flag canisr=canisr&0; return can_clean_success; } else { return can_clean_failure; } } /*-------------------------------------------------------------------------- routine name : can_fill_transmission_buffer input/output : -- / error status description : fills the hadrware buffer for transmission. comments : its have to be disabled called by can_transmit_request calls can_out_queue possible return values : can_transmit_buffer_full can_transmit_no_msg can_transmit_success --------------------------------------------------------------------------*/ can_transmit_error can_fill_transmission_buffer(void) { canpsr=page_1;
70/100 st7 pcan peripheral driver if (valbit(canbcsr,rdy)) //check if the register is already in use { return can_transmit_buffer_full; //exit if yes } else { can_buffer* msg_to_send_ptr; u8* data_ptr; can_data_size data_length; msg_to_send_ptr=can_out_queue(); //if no, get the first message in the queue if (msg_to_send_ptr==null) { return can_transmit_no_msg; //aborts process if queue empty } canidlr=0x00; canidhr=0x00; data_length=msg_to_send_ptr->data_size; data_ptr=msg_to_send_ptr->can_msg_data; //!!!code is here dependant of the order of the fields in the data structure //writing both canidhr and canidlr canidlr = *(((unsigned char*)msg_to_send_ptr)+1); canidhr = *((unsigned char*)msg_to_send_ptr); _asm("sll _canidlr \n rlc _canidhr"); { register u8 counter; if (data_length==remote_frame) /*if remote frame, send immediately*/ { setbit(canidlr,rtr); } else { canidlr |= data_length; for (counter=0;counter 71/100 st7 pcan peripheral driver candr[counter]=data_ptr[counter]; } } counter=7; candr[7]=data_ptr[counter]; } msg_to_send_ptr->buffer_free=ctrue; msg_to_send_ptr->buffer_rw=cfalse; } return can_transmit_success; } /*-------------------------------------------------------------------------- routine name : can_store_rcvd_msg input/output : id of the buffer to void/status message description : fetches the datas received in a hardware buffer. comments : its have to be disabled this fuction is called by can_recept, only in case of reception of datas priority given to speed here, that`s why the code may look strange possible return values : can_illegal_identifier can_receive_success --------------------------------------------------------------------------*/ static can_receive_error can_store_rcvd_msg(can_buffer* dest_ptr) { u8* data_ptr; u8 data_size; //canpsr=num_buff_hard; data_ptr=(dest_ptr->can_msg_data); data_size=(canidlr&0x0f); if(data_size>8) { clr_rdy_bit(); return can_illegal_identifier; } dest_ptr->data_size=data_size;//saving data size { register u8 counter;
72/100 st7 pcan peripheral driver for (counter=0;counter 73/100 st7 pcan peripheral driver message_ident = (((unsigned int)canidhr)<<8)|canidlr; message_ident >>= filter_shift; //appropriate rigth shift message_ident &= 0xfff0; //filtering function #ifdef filters_enabled /*conditionnal compilation*/ filtering_status=can_filter(message_ident); //filtering fonction call if (filtering_status==can_filter_no_match) { clr_rdy_bit(); //frees the hardware buffer for a new reception return can_filtering_failure; } #endif //tests if remote frame if(valbit(canidlr,4)) { clr_rdy_bit(); can_remote_reception_notification(message_ident); return can_receive_remote; } //else, saves the datas in a buffer passed by the application soft_buffer_ptr=can_request_buffer(message_ident); //requests a buffer for the messsage that successfully passed the filters if (soft_buffer_ptr==null) //the buffer must exist prior to beeing filled !!! { clr_rdy_bit(); return can_no_buffer; //kind of "software overrun" } if (soft_buffer_ptr->buffer_rw) { clr_rdy_bit(); return can_receive_fatal; } soft_buffer_ptr->buffer_rw=ctrue;//locks the buffer if (!(soft_buffer_ptr->buffer_free)) {
74/100 st7 pcan peripheral driver clr_rdy_bit(); soft_buffer_ptr->buffer_rw=cfalse;//if the buffer is full, releases it return can_receive_fatal; //and exit } receive_status=can_store_rcvd_msg(soft_buffer_ptr); //saves message and re- leases the hardware buffer //writing identifier : *(int*)soft_buffer_ptr = message_ident; //end of routine : if (receive_status!=can_receive_success) { clr_rdy_bit(); soft_buffer_ptr->buffer_rw=cfalse;//in case of failure, releases the buffer and exits return can_receive_fatal; } soft_buffer_ptr->buffer_free=cfalse; //in case of success, marks the buffer as in use soft_buffer_ptr->buffer_rw=cfalse; //unlock it can_data_reception_notification(message_ident); return can_receive_success; } /*-------------------------------------------------------------------------- routine name : can_interrupt input/output : -- /-- description : interrupt processing function comments : each case must be taken into account. calls can_get_it_type can_reception_notification can_transmission_notification can_fill_transmission_buffer can_dominant_bit_reception_notification may call (optionnal) : can_transmission_error_notification can_bus_passive_notification can_bus_active_notification can_bus_off_notification
75/100 st7 pcan peripheral driver can_overrun_notification can_general_reception_error_notification --------------------------------------------------------------------------*/ @interrupt @nostack void can_interrupt(void) { it_type it_type; it_type=can_get_it_type(); switch(it_type) { case itrecept : { can_receive_error error_status; if (valbit(canisr,rxif3)) //check the lower priority buffer first { status_counter=status_counter+1; error_status=can_receive(reception_3); #ifdef debug can_reception_status(error_status); #endif status_counter=status_counter-1; } if(valbit(canisr,rxif2)) //then checks the other { status_counter=status_counter+1; error_status=can_receive(reception_2); #ifdef debug can_reception_status(error_status); #endif status_counter=status_counter-1; } break; } case ittransmit : //transmission it { can_transmit_error status; clr_txif_bit();//clearing the flag status_counter=status_counter-1; //decrementing the status counter
76/100 st7 pcan peripheral driver can_transmission_notification(); status=can_it_fill_transmission_buffer(); #ifdef debug if (status!=can_transmit_success) { can_transmission_error_notification(status); // when an unsuccesfull transmission occured (argument : error status?) } #endif break; } case itscif : { can_status status; clr_scif_bit(); status=can_get_status(); if (status==can_standby) { can_dominant_bit_reception_notification(); //re- ception of a dominant bit while in stanby mode #ifndef status_change_notification clrbit(canicr,scie); //after first init, this it is no more needed if #endif / *status_change_notification is not requested*/ } #ifdef status_change_notification switch (status) { case can_bus_passive : can_bus_passive_notification(); //status change to bus passive break; case can_bus_active : can_bus_active_notification(); //status change to bus active break; case can_bus_off : can_bus_off_notification(); //response to a status change to bus-off break; default : /////////////////////////
77/100 st7 pcan peripheral driver //default case/////////// //should never happen//// //write debug code here// ///////////////////////// break; } #endif #ifdef general_reception_error { can_general_reception_error_notification(); clr_scif_bit(); } #endif break; } #ifdef debug case iterr : { if (valbit(canisr,orif)) { can_overrun_notification(); clr_orif_bit(); } else if (valbit(canisr,teif)) { can_transmission_error_notification(can_transmission_error_it); clr_teif_bit(); } break; } #endif default : ////////////////////////////////////////// //default case (should never be reached)// //debug code////////////////////////////// ////////////////////////////////////////// break; } } /* public functions
78/100 st7 pcan peripheral driver **********************************************************/ /* list of all functions defined in this module and used in other modules */ /*-------------------------------------------------------------------------- routine name : can_get_tec() input/output : -/value of the tecr register (transmission error counter) description : returns the value of the tecr register comments : --------------------------------------------------------------------------*/ u8 can_get_tec(void) { return cantecr; } /*-------------------------------------------------------------------------- routine name : can_get_rec() input/output : -/value of the recr register (reception error counter) description : returns the value of the tecr register comments : --------------------------------------------------------------------------*/ u8 can_get_rec(void) { return canrecr; } /*-------------------------------------------------------------------------- routine name : can_get_status input/output : -- / current status of the cell description : retrieves the current status of the can cell. comments : possible return values : can_standby can_bus_passive can_bus_off can_bus_active --------------------------------------------------------------------------*/ can_status can_get_status (void)
79/100 st7 pcan peripheral driver { if (!valbit(cancsr,run)) { return can_standby; } else { if (valbit(cancsr,epsv)) { return can_bus_passive; } else { if (valbit(cancsr,boff)) { return can_bus_off; } else return can_bus_active; } } } /*-------------------------------------------------------------------------- routine name : can_first_init input/output : --/ error status description : can cell power on initialisation routine. comments : calls can_init possible return value : can_init_failure can_init_success --------------------------------------------------------------------------*/ can_init_error can_first_init(void) { if (!valbit(cancsr,run)) //the can node is not running and there is an init structure { can_bool run_set,wkps_set; /*transmition queue init*/
80/100 st7 pcan peripheral driver can_queue_object_1.next_object=&can_queue_object_2; //the transmission objects are being linked can_queue_object_1.preceding_object=&can_queue_object_3; can_queue_object_1.message=null; can_queue_object_2.next_object=&can_queue_object_3; can_queue_object_2.preceding_object=&can_queue_object_1; can_queue_object_2.message=null; can_queue_object_3.next_object=&can_queue_object_1; can_queue_object_3.preceding_object=&can_queue_object_2; can_queue_object_3.message=null; can_transmit_queue.fifo_size=0; can_transmit_queue.first_object=&can_queue_object_1; can_transmit_queue.last_object=&can_queue_object_3; //has to be initial- ized that way, or the first input will fail can_transmit_queue.isinuse=cfalse; //releases queue canpsr=page_1; clr_lock_bit(); //cancels any pending transmission setbit(canbcsr,lock); //thus the buffer 2 cannot be used for reception //init of the hardware buffers run_set=cfalse; #ifdef run_on_start_up run_set=ctrue; #endif wkps_set=cfalse; #ifdef wake_up_pulse wkps_set=ctrue; #endif status_counter=0; #ifndef run_on_start_up canicr=canicr|0x08; //ie. a bus wake-up is wished #endif if(can_1_init(&first_init_data,run_set,wkps_set)==can_init_failure)
81/100 st7 pcan peripheral driver { return can_init_failure; } return can_init_success; } else return can_init_failure; } /*-------------------------------------------------------------------------- routine name : can_it_dis input/output : --/-- description : reset of the canicr register. comments : --------------------------------------------------------------------------*/ void can_it_dis (void) { canicr=0x00; } /*-------------------------------------------------------------------------- routine name : can_switch_off input/output : way the chip can be waken up : bus_wakeup or soft_wakeup/error status description : puts the can node into standby state. aborts any pending transmis- sion and doesn't wait for the reception buffer to having been read. a time out mechanism is implemented here (about 30ms). so if you use the watchdog in your application, refresh it before calling the fucntion ! comments : calls can_clean possible return value : can_sleep_success can_sleep_fatal --------------------------------------------------------------------------*/ can_switch_error can_switch_off(wakeup_cause wucause)
82/100 st7 pcan peripheral driver { can_clean_error clean_status; can_it_dis(); //resets the canicr register clrbit(cancsr,run); while (valbit(cancsr,run)) { static u16 counter=0xfff; //implement here a time out (171990 cpu cycles, ~21,4ms with 8mhz fcpu) counter=counter-1; if (counter==0) { return can_sleep_fatal; } } clean_status=can_clean(); if (clean_status==can_clean_failure) { return can_sleep_fatal; } if (wucause==bus_wakeup) //we are then in the case when the uc has to be waken up by the bus { clr_scif_bit(); //clears the canisr txif flag, before reenabling its setbit(canicr,scie); //sets the canicr txie flag, before reenabling its } else if(wucause==soft_wakeup) { clr_scif_bit(); //clears the canisr txif flag, before reenabling its } status_counter=0; return can_sleep_success; } /*-------------------------------------------------------------------------- routine name : can_sleep input/output : way the chip can be waken up : bus_wakeup or soft_wakeup/error status
83/100 st7 pcan peripheral driver description : puts the can node into passive state. returns an error if any transmission request is pendingor if a hardware reception buffer is still unsaved. dedicated to bus wake-up (for power save). comments : doesn't call can_clean. possible return values : can_sleep_error can_sleep_fatal can_sleep_success --------------------------------------------------------------------------*/ can_switch_error can_sleep (wakeup_cause wucause) { if (status_counter==0) { canpsr=page_2; setbit(canbcsr,lock); if (!valbit(canbcsr,lock)) { return can_sleep_error; } canpsr=page_3; setbit(canbcsr,lock); if (!valbit(canbcsr,lock)) { canpsr=page_2; clr_lock_bit(); return can_sleep_error; } //then the can cell can be shut down clrbit(cancsr,run); if (valbit(cancsr,run)) //be careful there !!!!! { return can_sleep_fatal; } canpsr=page_2; clr_lock_bit(); canpsr=page_3; clr_lock_bit(); if (wucause==bus_wakeup) //we are then in the case when the uc has to be waken up by the bus
84/100 st7 pcan peripheral driver { clr_scif_bit(); //clears the canisr txif flag, before reenabling its setbit(canicr,scie); /*sets the canicr txie flag, before reenabling its*/ } else if(wucause==soft_wakeup) { clr_scif_bit(); //clears the canisr txif flag, before reenabling its } return can_sleep_success; } return can_sleep_error; //default exit } /*-------------------------------------------------------------------------- routine name : can_switch_on input/output : pointer on an init data, order : emission of a dominant pulse by wake up or not/error status description : puts the can node into active state comments : calls can_init possible return value : switch_on_succes switch_on_failure --------------------------------------------------------------------------*/ can_switch_error can_switch_on (init_data_ptr idptr, can_bool wupulse_allowed) { if (!valbit(cancsr,run)) //the can must not be running { can_switch_error error_status; status_counter=0; canpsr=page_1; clr_lock_bit(); //cancels any pending transmission setbit(canbcsr,lock); //thus the buffer 1 cannot be used for reception
85/100 st7 pcan peripheral driver if (idptr!=null) //if null, nothing will be reinitialized { error_status=can_init(idptr,ctrue,wupulse_allowed); //run set automat- ically if (error_status==can_init_failure) { return can_switch_on_failure; } } return can_switch_on_succes; } else return can_switch_on_failure; } /*-------------------------------------------------------------------------- routine name : can_transmit_request input/output : pointer on the can buffer to send/error status description : puts a message into the queue, and may request an immediate transmission if it's void comments : calls can_init_queue and can_fill_transmission_buffer !!!this function must not be interrupted, so protect it with sim and rim statements when used outside the notification fuctions of can_custom.c!!! --------------------------------------------------------------------------*/ can_transmit_error can_transmit_request(can_buffer* msg_to_send_ptr) { can_transmit_error status; if (msg_to_send_ptr->buffer_rw==ctrue) { return can_transmit_failure; } msg_to_send_ptr->buffer_rw=ctrue; if (!valbit(cancsr,run)) //no transmission autorized when the can cell is not running {
86/100 st7 pcan peripheral driver msg_to_send_ptr->buffer_rw=cfalse; return can_transmit_failure; } status=can_in_queue(msg_to_send_ptr); //puts the message in the queue if (status==can_fifo_full) { msg_to_send_ptr->buffer_rw=cfalse; return status; } status_counter=status_counter+1; status=can_fill_transmission_buffer(); //tries to fill the buffer 2 if (status==can_transmit_no_msg) //this should never happen { status_counter=status_counter-1; msg_to_send_ptr->buffer_rw=cfalse; return can_transmit_fatal; } else { return status; //can be success or buffer in use (ie. a request is already pending) } //the modif of buffer_rw will be executed by can_store_received_message } /****** (c) 2000 stmicroelectronics ********************* end of file _******/ 4.2 can.h /*********************** (c) 2000 stmicroelectronics ************************* project : compiler : st7 cosmic c v4.2e module : can.h version : v 1.1.6 build 80 creation date : 04/00
87/100 st7 pcan peripheral driver author : central europe 8bit micro application group -*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- description : can routines -*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- modifications : none *************************************************************************** the software included in this file is for guidance only. st microelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from use of this software. ***************************************************************************/ #ifndef can_h #define can_h #define can_max_data_size 8 #ifndef _h_stddef_ #define null (void*) 0 /*not already defined if stddef.h not included*/ #endif #define null_defined / *########################################################################### */ /* typedef */ / *########################################################################### */ ///////////////////// //simple data types// ///////////////////// typedef enum {bus_wakeup,soft_wakeup}wakeup_cause; typedef enum {dlc0,dlc1,dlc2,dlc3,dlc4,dlc5,dlc6,dlc7,dlc8,remote_frame}can_data_size;
88/100 st7 pcan peripheral driver //error status messages //initialisation typedef enum {can_init_success,can_init_failure}can_init_error; //sleep typedef enum {can_sleep_fatal,can_sleep_error,can_sleep_success,can_switch_on_succes,can_ switch_on_failure}can_switch_error; //status typedef enum {can_run,can_standby,can_bus_active,can_bus_passive,can_bus_off}can_status; //misc. typedef enum {cfalse=0,ctrue=1}can_bool; //transmission-reception typedef enum {can_transmit_fatal,can_transmit_success,can_transmit_failure,can_transmit_n o_msg,can_fifo_full,can_transmit_buffer_full,can_transmission_error_it}can_t ransmit_error; typedef enum {can_receive_fatal,can_receive_success,can_receive_remote,can_illegal_identi fier,can_filtering_failure,can_buffer_in_use,can_no_buffer,can_rcv_buffer_no t_ready}can_receive_error; ////////////////////////////////////// //transmission/reception structures // ////////////////////////////////////// //input/output structure typedef struct can_buffer{ u16 msg_identifier; can_data_size data_size; u8 can_msg_data[can_max_data_size]; can_bool buffer_rw; can_bool buffer_free; //shared variable }can_buffer; ///////////////////////////// //initialization parameters// ///////////////////////////// //initialisation data structure typedef struct { u8 brpr_init; u8 btr_init; u8 fhr1_init;
89/100 st7 pcan peripheral driver u8 flr1_init; u8 mhr1_init; u8 mlr1_init; u8 fhr0_init; u8 flr0_init; u8 mhr0_init; u8 mlr0_init; }init_data; typedef init_data* init_data_ptr; // pointer on an init_data structure / *#########################################################################*/ /* variables */ / *#########################################################################*/ //initialization of the can-cell //variables declared in can.c extern const init_data first_init_data; //initialisation datas used at power-on extern const u16 i_filters[]; // array of accepted filters / *#########################################################################*/ /* functions */ / *#########################################################################*/ //power-on initialisation can_init_error can_first_init(void); //resets it authorization flags void can_it_dis(void); //gets state of the cell : active, passive, off can_status can_get_status (void); //gets value of transmit error counter & reception error counter u8 can_get_tec(void); u8 can_get_rec(void); //modification of the cell state can_switch_error can_switch_off(wakeup_cause); can_switch_error can_sleep (wakeup_cause); can_switch_error can_switch_on(init_data_ptr,can_bool);
90/100 st7 pcan peripheral driver //transmission request can_transmit_error can_transmit_request(can_buffer*); / *#########################################################################*/ /* macros */ / *#########################################################################*/ //to clear status registers flags #define clr_rxif3_bit() (canisr=0x7f) #define clr_rxif2_bit() (canisr=0xbf) #define clr_rxif1_bit() (canisr=0xdf) #define clr_txif_bit() (canisr=0xef) #define clr_scif_bit() (canisr=0xf7) #define clr_orif_bit() (canisr=0xfb) #define clr_teif_bit() (canisr=0xfd) #define clr_epnd_bit() (canisr=0xfe) //to clear #define clr_lock_bit() (canbcsr=0xfe) #define clr_rdy_bit() (canbcsr=0xfa) #define size_of_words_array(array) sizeof(array)/sizeof(unsigned int) /*----------------------can settings----------------------*/ #define can_run_cell() (cancsr |= 0x05) #endif /****** (c) 2000 stmicroelectronics ********************* end of file _******/ 4.3 can_custom.c /********************* (c) 1999 stmicroelectronics**************************** /********************* (c) 1999 stmicroelectronics ***************************
91/100 st7 pcan peripheral driver project : compiler : st7 cosmic c v4.2e module : can_custom.c version : 1.1.6 build 44 creation date : 04/99 author : central europe 8bit micro application group -*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- description : customisation functions for can driver -*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- modifications : **************************************************************************** the software included in this file is for guidance only. st microelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from use of this software. ***************************************************************************/ #include "lib.h" #include "can.h" #include "sci.h" #include "can_custom.h" #include "gateway.h" #include "interface.h" /////////////////////////// //preprocessor directives// /////////////////////////// //////////////////////////////////////// //variables///////////////////////////// ////////////////////////////////////////
92/100 st7 pcan peripheral driver ////////////////////////////////////////////////////////// //optional functions//////////////////////////////////// ////////////////////////////////////////////////////////// //all those functions are meant to be called by the interrupt routine //so don't auhorize its in this file, otherwise it could lead to undefined behaviour //of the application can_buffer* can_request_buffer(u16 ident_of_message) { //the application must supply here a buffer. } void can_remote_reception_notification(u16 ident_of_remote) { //application behaviour after reception of a remote frame } void can_data_reception_notification(u16 message_ident) { //application behaviour after reception of a data frame } void can_transmission_notification(void) { //write your code here } void can_dominant_bit_reception_notification(void) { //write your code here } #ifdef status_change_notification void can_bus_passive_notification(void) { //to implement if defined } void can_bus_active_notification(void) {
93/100 st7 pcan peripheral driver //to implement if defined } void can_bus_off_notification(void) { //to implement if defined } #endif #ifdef general_reception_error void can_general_reception_error_notification(void) { //to implement if defined } #endif #ifdef debug void can_reception_status(can_receive_error status) { //to implement if defined } void can_overrun_notification(void) { //to implement if defined } void can_transmission_error_notification(can_transmit_error status) { //to implement if defined } #endif /******** (c) 1999 stmicroelectronics ****************** end of file ********/ 4.4 can_custom.h /*********************** (c) 1999 stmicroelectronics ************************* project: compiler: st7 cosmic c v.4.2e module: can_custom.h version: v 1.1.6 build 44 creation date: 04/00 author: central europe 8bit micro application group
94/100 st7 pcan peripheral driver -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*- description: can customization options -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*- modifications: none **************************************************************************** the software included in this file is for guidance only. st microelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from use of this software. ***************************************************************************/ #ifndef can_custom_h #define can_custom_h ////////////////// //custom defines// ////////////////// / *#########################################################################*/ /* preprocessor directives */ / *#########################################################################*/ //first initialization /*timing*/ #define init_brpr 0x00 #define init_btr 0x00 //start options //#define wake_up_pulse /*shall the can cell emit a dominant pulse by wake-up?*/ #define run_on_start_up /*shall the cell run immediately or wait for a bus event?*/ /*masks & filters*/ #define init_fhr0 0x00 #define init_flr0 0x00 #define init_mhr0 0x00
95/100 st7 pcan peripheral driver #define init_mlr0 0x00 #define init_fhr1 0x00 #define init_flr1 0x00 #define init_mhr1 0x00 #define init_mlr1 0x00 //software acceptance masks //#define filters_enabled //#define init_filters {} /*max identifier : 2048, that's to say 0x0800, max size of the array :127*/ //its compilation options //have to be disabled if a direct implementation of the it function //is meant //enabling one of these options implies coding the corresponding function in the can_custom.c file //the choice will determine the initialization of the status register //to monitor status changes //#define status_change_notification //to use other error notifications functions: //#define debug //#define general_reception_error /*if defined, replaces the status change interrupts*/ //only if debug also defined //does not exclude bus wake-up feature //#define simultaneous_emission_reception /*only if debug also defined*/ //allows simultaneous reception and reception of a message //to check the integrity of the message path / *#########################################################################*/ /* variables */ / *#########################################################################*/ /*----------------------can settings----------------------*/ #endif /****** (c) 1999 stmicroelectronics ********************* end of file _******/
96/100 st7 pcan peripheral driver 4.5 can_hr.h /*********************** (c) 2000 stmicroelectronics ************************* project : compiler : st7 cosmic c v.4.2e module : can.c version : v 1.1.6 build 44 creation date : 04/00 author : central europe 8bit micro application group -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- description : can hardware registers -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- modifications : **************************************************************************** the software included in this file is for guidance only. st microelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from use of this software. ***************************************************************************/ #ifndef can_hr_h #define can_hr_h /*---------------------------register declaration---------------------------- */ /* controller area network */ @tiny volatile unsigned char canisr @0x5a; /* interrupt status register */ @tiny volatile unsigned char canicr @0x5b; /* interrupt control register */ @tiny volatile unsigned char cancsr @0x5c; /* control status register */ @tiny volatile unsigned char canbrpr @0x5d; /* baud rate prescaler register */ @tiny volatile unsigned char canbtr @0x5e; /* bit timing register */ @tiny volatile unsigned char canpsr @0x5f; /* page selection register */ /* controller area network paged registers */ /* page 0 */ @tiny volatile unsigned char canlidhr @0x60; /* last identifier high register */ @tiny volatile unsigned char canlidlr @0x61; /* last identifier low register */
97/100 st7 pcan peripheral driver @tiny volatile unsigned char canres00 @0x62; /* reserved */ @tiny volatile unsigned char canres01 @0x63; /* reserved */ @tiny volatile unsigned char canres02 @0x64; /* reserved */ @tiny volatile unsigned char canres03 @0x65; /* reserved */ @tiny volatile unsigned char canres04 @0x66; /* reserved */ @tiny volatile unsigned char canres05 @0x67; /* reserved */ @tiny volatile unsigned char canres06 @0x68; /* reserved */ @tiny volatile unsigned char canres07 @0x69; /* reserved */ @tiny volatile unsigned char canres08 @0x6a; /* reserved */ @tiny volatile unsigned char canres09 @0x6b; /* reserved */ @tiny volatile unsigned char canres010 @0x6c; /* reserved */ @tiny volatile unsigned char cantstr @0x6d; /* reserved */ @tiny volatile unsigned char cantecr @0x6e; /* transmit error counter */ @tiny volatile unsigned char canrecr @0x6f; /* receive error counter */ /* pages 1,2,3: identifiers */ @tiny volatile unsigned char canidhr @0x60; /* identifier high register */ @tiny volatile unsigned char canidlr @0x61; /* identifier low register */ /* pages 1,2,3: data */ @tiny volatile unsigned char candr[8] @0x62; /* 8 data registers */ @tiny volatile unsigned char canres1230 @0x6a; /* reserved */ @tiny volatile unsigned char canres1231 @0x6b; /* reserved */ @tiny volatile unsigned char canres1232 @0x6c; /* reserved */ @tiny volatile unsigned char canres1233 @0x6d; /* reserved */ @tiny volatile unsigned char canres1234 @0x6e; /* reserved */ @tiny volatile unsigned char canbcsr @0x6f; /* buffer control status register*/ /* buffers */ @tiny volatile unsigned char canfhr0 @0x60; /* filter 0 high register */ @tiny volatile unsigned char canflr0 @0x61; /* filter 0 low register */ @tiny volatile unsigned char canmhr0 @0x62; /* mask 0 high register */ @tiny volatile unsigned char canmlr0 @0x63; /* mask 0 low register */ @tiny volatile unsigned char canfhr1 @0x64; /* filter 1 high register */ @tiny volatile unsigned char canflr1 @0x65; /* filter 1 low register */ @tiny volatile unsigned char canmhr1 @0x66; /* mask 1 high register */ @tiny volatile unsigned char canmlr1 @0x67; /* mask 1 low register */ /*-------------------------register bits definition-------------------------- */ #define rxif3 7 /* interrupt status register */ #define rxif2 6 #define rxif1 5
98/100 st7 pcan peripheral driver #define txif 4 #define scif 3 #define orif 2 #define teif 1 #define epnd 0 #define esci 6 /* interrupt control register */ #define rxie 5 #define txie 4 #define scie 3 #define orie 2 #define teie 1 #define etx 0 #define boff 6 /* control status register */ #define epsv 5 #define srte 4 #define nrtx 3 #define fsyn 2 #define wkps 1 #define run 0 #define rjw1 7 /* baud rate prescaler register */ #define rjw0 6 #define brp5 5 #define brp4 4 #define brp3 3 #define brp2 2 #define brp1 1 #define brp0 0 #define bs22 6 /* bit timing register */ #define bs21 5 #define bs20 4 #define bs13 3 #define bs12 2 #define bs11 1 #define bs10 0 #define page0 0 /* page selection register */ #define page1 1 #define page2 2 #define page3 3 #define page4 4
99/100 st7 pcan peripheral driver #define rtr 4 #define msk_dlc 0x0f /* identifier low register */ #define acc 3 /* buffer control status register */ #define rdy 2 /* buffer control status register */ #define busy 1 #define lock 0 /*------------------------------------------------------------------------*/ #endif /****** (c) 2000 stmicroelectronics ********************* end of file _******/
100/100 st7 pcan peripheral driver "the present note which is for guidance only aims at providing cus- tomers with information regarding their products in order for them to save time. as a result, stmicroelectronics shall not be held liable for any direct, indirect or consequential damages with respect to any claims arising from the content of such a note and/or the use made by customers of the information contained herein in connexion with their products." information furnished is believed to be accurate and reliable. however, stmicroelectronics assumes no responsibility for the co nsequences of use of such information nor for any infringement of patents or other rights of third parties which may result from its use. no license is granted by implication or otherwise under any patent or patent rights of stmicroelectronics. specifications mentioned in this publicati on are subject to change without notice. this publication supersedes and replaces all information previously supplied. stmicroelectronics prod ucts are not authorized for use as critical components in life support devices or systems without the express written approval of stmicroele ctronics. the st logo is a registered trademark of stmicroelectronics ? 2001 stmicroelectronics - all rights reserved. purchase of i 2 c components by stmicroelectronics conveys a license under the philips i 2 c patent. rights to use these components in an i 2 c system is granted provided that the system conforms to the i 2 c standard specification as defined by philips. stmicroelectronics group of companies australia - brazil - china - finland - france - germany - hong kong - india - italy - japan - malaysia - malta - morocco - sin gapore - spain sweden - switzerland - united kingdom - u.s.a. http://www.st.com


▲Up To Search▲   

 
Price & Availability of AN1105

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X